Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Fix ignore files in file upload and added tests (#1012)

Mish Ushakov56d16a87620d
diff --git a/.changeset/old-carrots-greet.md b/.changeset/old-carrots-greet.md
new file mode 100644
index 000000000..b7eff3ddc
--- /dev/null
+++ b/.changeset/old-carrots-greet.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+fixes ignore files in file upload
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index 9403c073b..505817db1 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -91,15 +91,18 @@ export async function uploadFile(
fileName: string
fileContextPath: string
url: string
+ ignorePatterns: string[]
resolveSymlinks: boolean
},
stackTrace: string | undefined
) {
- const { fileName, url, fileContextPath, resolveSymlinks } = options
+ const { fileName, url, fileContextPath, ignorePatterns, resolveSymlinks } =
+ options
try {
const { contentLength, uploadStream } = await tarFileStreamUpload(
fileName,
fileContextPath,
+ ignorePatterns,
resolveSymlinks
)
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 91bfbe17c..177ffc131 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -925,6 +925,10 @@ export class TemplateBase
fileName: src,
fileContextPath: this.fileContextPath.toString(),
url,
+ ignorePatterns: [
+ ...this.fileIgnorePatterns,
+ ...readDockerignore(this.fileContextPath.toString()),
+ ],
resolveSymlinks: instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
},
stackTrace
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index 3bd0e047a..4ab359465 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -32,10 +32,11 @@ export function readDockerignore(contextPath: string): string[] {
* @param ignorePatterns Ignore patterns
* @returns Array of files
*/
-export async function getAllFilesForFilesHash(
+export async function getAllFilesInPath(
src: string,
contextPath: string,
- ignorePatterns: string[]
+ ignorePatterns: string[],
+ includeDirectories: boolean = true
) {
const { glob } = await dynamicGlob()
const files = new Map<string, Path>()
@@ -50,7 +51,9 @@ export async function getAllFilesForFilesHash(
for (const file of globFiles) {
if (file.isDirectory()) {
// For directories, add the directory itself and all files inside it
- files.set(file.fullpath(), file)
+ if (includeDirectories) {
+ files.set(file.fullpath(), file)
+ }
const dirFiles = await glob(
path.join(path.relative(contextPath, file.fullpath()), '**/*'),
{
@@ -97,7 +100,7 @@ export async function calculateFilesHash(
hash.update(content)
- const files = await getAllFilesForFilesHash(src, contextPath, ignorePatterns)
+ const files = await getAllFilesInPath(src, contextPath, ignorePatterns, true)
if (files.length === 0) {
const error = new Error(`No files found in ${srcPath}`)
@@ -233,25 +236,37 @@ export function padOctal(mode: number): string {
*
* @param fileName Glob pattern for files to include
* @param fileContextPath Base directory for resolving file paths
+ * @param ignorePatterns Ignore patterns to exclude from the archive
* @param resolveSymlinks Whether to follow symbolic links
* @returns A readable stream of the gzipped tar archive
*/
export async function tarFileStream(
fileName: string,
fileContextPath: string,
+ ignorePatterns: string[],
resolveSymlinks: boolean
) {
- const { globSync } = await dynamicGlob()
const { create } = await dynamicTar()
- const files = globSync(fileName, { cwd: fileContextPath })
+
+ const allFiles = await getAllFilesInPath(
+ fileName,
+ fileContextPath,
+ ignorePatterns,
+ true
+ )
+
+ const filePaths = allFiles.map((file) =>
+ path.relative(fileContextPath, file.fullpath())
+ )
return create(
{
gzip: true,
cwd: fileContextPath,
follow: resolveSymlinks,
+ noDirRecurse: true,
},
- files
+ filePaths
)
}
@@ -266,12 +281,14 @@ export async function tarFileStream(
export async function tarFileStreamUpload(
fileName: string,
fileContextPath: string,
+ ignorePatterns: string[],
resolveSymlinks: boolean
) {
// First pass: calculate the compressed size
const sizeCalculationStream = await tarFileStream(
fileName,
fileContextPath,
+ ignorePatterns,
resolveSymlinks
)
let contentLength = 0
@@ -284,6 +301,7 @@ export async function tarFileStreamUpload(
uploadStream: await tarFileStream(
fileName,
fileContextPath,
+ ignorePatterns,
resolveSymlinks
),
}
diff --git a/packages/js-sdk/tests/template/utils/getAllFilesForFilesHash.test.ts b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
similarity index 91%
rename from packages/js-sdk/tests/template/utils/getAllFilesForFilesHash.test.ts
rename to packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
index 797ff6a83..3f14a7239 100644
--- a/packages/js-sdk/tests/template/utils/getAllFilesForFilesHash.test.ts
+++ b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
@@ -1,9 +1,9 @@
import { expect, test, describe, beforeAll, afterAll, beforeEach } from 'vitest'
import { writeFile, mkdir, rm } from 'fs/promises'
import { join } from 'path'
-import { getAllFilesForFilesHash } from '../../../src/template/utils'
+import { getAllFilesInPath } from '../../../src/template/utils'
-describe('getAllFilesForFilesHash', () => {
+describe('getAllFilesInPath', () => {
const testDir = join(__dirname, 'folder')
beforeAll(async () => {
@@ -26,7 +26,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'file2.txt'), 'content2')
await writeFile(join(testDir, 'file3.js'), 'content3')
- const files = await getAllFilesForFilesHash('*.txt', testDir, [])
+ const files = await getAllFilesInPath('*.txt', testDir, [])
expect(files).toHaveLength(2)
expect(files.some((f) => f.fullpath().endsWith('file1.txt'))).toBe(true)
@@ -51,7 +51,7 @@ describe('getAllFilesForFilesHash', () => {
)
await writeFile(join(testDir, 'README.md'), 'readme content')
- const files = await getAllFilesForFilesHash('src', testDir, [])
+ const files = await getAllFilesInPath('src', testDir, [])
expect(files).toHaveLength(6) // 3 files + 3 directories (src, components, utils)
expect(files.some((f) => f.fullpath().endsWith('index.ts'))).toBe(true)
@@ -67,7 +67,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'temp.txt'), 'temp content')
await writeFile(join(testDir, 'backup.txt'), 'backup content')
- const files = await getAllFilesForFilesHash('*.txt', testDir, [
+ const files = await getAllFilesInPath('*.txt', testDir, [
'temp*',
'backup*',
])
@@ -105,7 +105,7 @@ describe('getAllFilesForFilesHash', () => {
'spec content'
)
- const files = await getAllFilesForFilesHash('src', testDir, [
+ const files = await getAllFilesInPath('src', testDir, [
'**/*.test.*',
'**/*.spec.*',
])
@@ -126,7 +126,7 @@ describe('getAllFilesForFilesHash', () => {
await mkdir(join(testDir, 'empty'), { recursive: true })
await writeFile(join(testDir, 'file.txt'), 'content')
- const files = await getAllFilesForFilesHash('empty', testDir, [])
+ const files = await getAllFilesInPath('empty', testDir, [])
expect(files).toHaveLength(1) // The empty directory itself
})
@@ -138,7 +138,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'dir1', 'file2.txt'), 'content2')
await writeFile(join(testDir, 'file3.txt'), 'content3')
- const files = await getAllFilesForFilesHash('*', testDir, [])
+ const files = await getAllFilesInPath('*', testDir, [])
expect(files).toHaveLength(4) // 3 files + 1 directory
expect(files.some((f) => f.fullpath().endsWith('file1.txt'))).toBe(true)
@@ -166,7 +166,7 @@ describe('getAllFilesForFilesHash', () => {
'css content'
)
- const files = await getAllFilesForFilesHash('src/**/*', testDir, [])
+ const files = await getAllFilesInPath('src/**/*', testDir, [])
expect(files).toHaveLength(6) // 4 files + 2 directories (components, utils)
expect(files.some((f) => f.fullpath().endsWith('index.ts'))).toBe(true)
@@ -181,7 +181,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'file3.tsx'), 'tsx content')
await writeFile(join(testDir, 'file4.css'), 'css content')
- const files = await getAllFilesForFilesHash('*.ts', testDir, [])
+ const files = await getAllFilesInPath('*.ts', testDir, [])
expect(files).toHaveLength(1)
expect(files.some((f) => f.fullpath().endsWith('file1.ts'))).toBe(true)
@@ -192,7 +192,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'apple.txt'), 'a content')
await writeFile(join(testDir, 'banana.txt'), 'b content')
- const files = await getAllFilesForFilesHash('*.txt', testDir, [])
+ const files = await getAllFilesInPath('*.txt', testDir, [])
expect(files).toHaveLength(3)
// Files are sorted by full path, not just filename
@@ -203,7 +203,7 @@ describe('getAllFilesForFilesHash', () => {
test('should handle no matching files', async () => {
await writeFile(join(testDir, 'file.txt'), 'content')
- const files = await getAllFilesForFilesHash('*.js', testDir, [])
+ const files = await getAllFilesInPath('*.js', testDir, [])
expect(files).toHaveLength(0)
})
@@ -232,7 +232,7 @@ describe('getAllFilesForFilesHash', () => {
await writeFile(join(testDir, 'dist', 'bundle.js'), 'bundle content')
await writeFile(join(testDir, 'README.md'), 'readme content')
- const files = await getAllFilesForFilesHash('src', testDir, [
+ const files = await getAllFilesInPath('src', testDir, [
'**/tests/**',
'**/*.spec.*',
])
diff --git a/packages/js-sdk/tests/template/utils/tarFileStream.test.ts b/packages/js-sdk/tests/template/utils/tarFileStream.test.ts
new file mode 100644
index 000000000..7628c5dd3
--- /dev/null
+++ b/packages/js-sdk/tests/template/utils/tarFileStream.test.ts
@@ -0,0 +1,231 @@
+import { expect, test, describe, beforeAll, afterAll, beforeEach } from 'vitest'
+import { writeFile, mkdir, rm, symlink, readFile } from 'fs/promises'
+import { createWriteStream } from 'fs'
+import { join } from 'path'
+import { tmpdir } from 'os'
+import { pipeline } from 'stream/promises'
+import { tarFileStream } from '../../../src/template/utils'
+import { dynamicTar } from '../../../src/utils'
+import { ReadEntry } from 'tar'
+
+describe('tarFileStream', () => {
+ const testDir = join(__dirname, 'tar-test-folder')
+
+ beforeAll(async () => {
+ await rm(testDir, { recursive: true, force: true })
+ await mkdir(testDir, { recursive: true })
+ })
+
+ afterAll(async () => {
+ await rm(testDir, { recursive: true, force: true })
+ })
+
+ beforeEach(async () => {
+ await rm(testDir, { recursive: true, force: true })
+ await mkdir(testDir, { recursive: true })
+ })
+
+ /**
+ * Extract tar contents into a dictionary mapping paths to file contents.
+ */
+ async function extractTarContents(
+ stream: any
+ ): Promise<Map<string, Buffer | null>> {
+ // Write stream to a temporary file (like Python's BytesIO)
+ const tarFile = join(tmpdir(), `tar-test-${Date.now()}.tar.gz`)
+ const writeStream = createWriteStream(tarFile)
+ await pipeline(stream, writeStream)
+
+ const tar = await dynamicTar()
+ const contents = new Map<string, Buffer | null>()
+
+ // Extract files to a temp directory and collect members
+ const extractDir = join(tmpdir(), `tar-extract-${Date.now()}`)
+ await mkdir(extractDir, { recursive: true })
+
+ const members: ReadEntry[] = []
+ await tar.extract({
+ file: tarFile,
+ cwd: extractDir,
+ gzip: true,
+ onentry: (entry: ReadEntry) => {
+ members.push(entry)
+ },
+ })
+
+ // Read file contents
+ for (const member of members) {
+ if (member.type === 'File') {
+ const filePath = join(extractDir, member.path)
+ try {
+ const content = await readFile(filePath)
+ contents.set(member.path, content)
+ } catch {
+ // File might not exist
+ }
+ } else if (member.type === 'Directory') {
+ contents.set(member.path, null)
+ } else if (member.type === 'SymbolicLink') {
+ contents.set(member.path, Buffer.from(member.linkpath || ''))
+ }
+ }
+
+ // Cleanup
+ await rm(tarFile, { force: true })
+ await rm(extractDir, { recursive: true, force: true })
+
+ return contents
+ }
+
+ /**
+ * Get tar members
+ */
+ async function getTarMembers(stream: any): Promise<Map<string, ReadEntry>> {
+ // Write stream to a temporary file
+ const tarFile = join(tmpdir(), `tar-test-${Date.now()}.tar.gz`)
+ const writeStream = createWriteStream(tarFile)
+ await pipeline(stream, writeStream)
+
+ const tar = await dynamicTar()
+ const members = new Map<string, ReadEntry>()
+
+ const extractDir = join(tmpdir(), `tar-extract-${Date.now()}`)
+ await mkdir(extractDir, { recursive: true })
+
+ await tar.extract({
+ file: tarFile,
+ cwd: extractDir,
+ gzip: true,
+ onentry: (entry: ReadEntry) => {
+ members.set(entry.path, entry)
+ },
+ })
+
+ // Cleanup
+ await rm(tarFile, { force: true })
+ await rm(extractDir, { recursive: true, force: true })
+
+ return members
+ }
+
+ test('should create tar with simple files', async () => {
+ // Create test files
+ await writeFile(join(testDir, 'file1.txt'), 'content1')
+ await writeFile(join(testDir, 'file2.txt'), 'content2')
+
+ const stream = await tarFileStream('*.txt', testDir, [], false)
+ const contents = await extractTarContents(stream)
+
+ expect(contents.size).toBe(2)
+ expect(contents.has('file1.txt')).toBe(true)
+ expect(contents.has('file2.txt')).toBe(true)
+ expect(contents.get('file1.txt')?.toString()).toBe('content1')
+ expect(contents.get('file2.txt')?.toString()).toBe('content2')
+ })
+
+ test('should respect ignore patterns', async () => {
+ // Create test files
+ await writeFile(join(testDir, 'file1.txt'), 'content1')
+ await writeFile(join(testDir, 'file2.txt'), 'content2')
+ await writeFile(join(testDir, 'temp.txt'), 'temp content')
+ await writeFile(join(testDir, 'backup.txt'), 'backup content')
+
+ const stream = await tarFileStream(
+ '*.txt',
+ testDir,
+ ['temp*', 'backup*'],
+ false
+ )
+ const contents = await extractTarContents(stream)
+
+ expect(contents.size).toBe(2)
+ expect(contents.has('file1.txt')).toBe(true)
+ expect(contents.has('file2.txt')).toBe(true)
+ expect(contents.get('file1.txt')?.toString()).toBe('content1')
+ expect(contents.get('file2.txt')?.toString()).toBe('content2')
+ expect(contents.has('temp.txt')).toBe(false)
+ expect(contents.has('backup.txt')).toBe(false)
+ })
+
+ test('should handle nested files', async () => {
+ // Create nested directory structure
+ const nestedDir = join(testDir, 'src', 'components')
+ await mkdir(nestedDir, { recursive: true })
+
+ await writeFile(join(testDir, 'src', 'index.ts'), 'index content')
+ await writeFile(join(nestedDir, 'Button.tsx'), 'button content')
+
+ const stream = await tarFileStream('src', testDir, [], false)
+ const contents = await extractTarContents(stream)
+
+ // Should include the directory and files
+ const paths = Array.from(contents.keys())
+ expect(paths.some((p) => p.includes('src'))).toBe(true)
+ expect(paths.some((p) => p.includes('index.ts'))).toBe(true)
+ expect(paths.some((p) => p.includes('Button.tsx'))).toBe(true)
+ })
+
+ test('should resolve symlinks when enabled', async () => {
+ // Create original file
+ const originalPath = join(testDir, 'original.txt')
+ await writeFile(originalPath, 'original content')
+
+ // Create symlink
+ const symlinkPath = join(testDir, 'link.txt')
+ try {
+ await symlink('original.txt', symlinkPath)
+ } catch (error: any) {
+ // Skip test if symlinks are not supported on this platform
+ if (error.code === 'ENOSYS' || error.code === 'EPERM') {
+ return
+ }
+ throw error
+ }
+
+ // Test with resolveSymlinks=true
+ const stream = await tarFileStream('*.txt', testDir, [], true)
+ const contents = await extractTarContents(stream)
+
+ // Both files should be in tar
+ expect(contents.has('original.txt')).toBe(true)
+ expect(contents.has('link.txt')).toBe(true)
+ // Symlink should be resolved (contain actual content, not link)
+ expect(contents.get('original.txt')?.toString()).toBe('original content')
+ expect(contents.get('link.txt')?.toString()).toBe('original content')
+ })
+
+ test('should preserve symlinks when disabled', async () => {
+ // Create original file
+ const originalPath = join(testDir, 'original.txt')
+ await writeFile(originalPath, 'original content')
+
+ // Create symlink
+ const symlinkPath = join(testDir, 'link.txt')
+ try {
+ await symlink('original.txt', symlinkPath)
+ } catch (error: any) {
+ // Skip test if symlinks are not supported on this platform
+ if (error.code === 'ENOSYS' || error.code === 'EPERM') {
+ return
+ }
+ throw error
+ }
+
+ // Test with resolveSymlinks=false
+ const stream = await tarFileStream('*.txt', testDir, [], false)
+ const members = await getTarMembers(stream)
+
+ // Both files should be in tar
+ expect(members.has('original.txt')).toBe(true)
+ expect(members.has('link.txt')).toBe(true)
+
+ // Original should be a regular file
+ const original = members.get('original.txt')!
+ expect(original.type).toBe('File')
+
+ // Link should be a symlink
+ const link = members.get('link.txt')!
+ expect(link.type).toBe('SymbolicLink')
+ expect(link.linkpath).toBe('original.txt')
+ })
+})
diff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.py
index 5c2a239ae..68c6726b1 100644
--- a/packages/python-sdk/e2b/template/utils.py
+++ b/packages/python-sdk/e2b/template/utils.py
@@ -1,5 +1,7 @@
import hashlib
import os
+import io
+import tarfile
import json
import stat
from wcmatch import glob
@@ -33,8 +35,11 @@ def read_dockerignore(context_path: str) -> List[str]:
]
-def get_all_files_for_files_hash(
- src: str, context_path: str, ignore_patterns: List[str]
+def get_all_files_in_path(
+ src: str,
+ context_path: str,
+ ignore_patterns: List[str],
+ include_directories: bool = True,
) -> List[str]:
"""
Get all files for a given path and ignore patterns.
@@ -42,6 +47,7 @@ def get_all_files_for_files_hash(
:param src: Path to the source directory
:param context_path: Base directory for resolving relative paths
:param ignore_patterns: Ignore patterns
+ :param include_directories: Whether to include directories
:return: Array of files
"""
files = set()
@@ -61,7 +67,8 @@ def get_all_files_for_files_hash(
if os.path.isdir(file_path):
# If it's a directory, add the directory and all entries recursively
- files.add(file_path)
+ if include_directories:
+ files.add(file_path)
dir_files = glob.glob(
os.path.join(file, "**/*"),
flags=glob.GLOBSTAR,
@@ -108,7 +115,7 @@ def calculate_files_hash(
hash_obj.update(content.encode())
- files = get_all_files_for_files_hash(src, context_path, ignore_patterns)
+ files = get_all_files_in_path(src, context_path, ignore_patterns, True)
if len(files) == 0:
raise ValueError(f"No files found in {src_path}").with_traceback(stack_trace)
@@ -148,6 +155,39 @@ def calculate_files_hash(
return hash_obj.hexdigest()
+def tar_file_stream(
+ file_name: str,
+ file_context_path: str,
+ ignore_patterns: List[str],
+ resolve_symlinks: bool,
+) -> io.BytesIO:
+ """
+ Create a tar stream of files matching a pattern.
+
+ :param file_name: Glob pattern for files to include
+ :param file_context_path: Base directory for resolving file paths
+ :param ignore_patterns: Ignore patterns
+ :param resolve_symlinks: Whether to resolve symbolic links
+
+ :return: Tar stream
+ """
+ tar_buffer = io.BytesIO()
+ with tarfile.open(
+ fileobj=tar_buffer,
+ mode="w:gz",
+ dereference=resolve_symlinks,
+ ) as tar:
+ files = get_all_files_in_path(
+ file_name, file_context_path, ignore_patterns, True
+ )
+ for file in files:
+ tar.add(
+ file, arcname=os.path.relpath(file, file_context_path), recursive=False
+ )
+
+ return tar_buffer
+
+
def strip_ansi_escape_codes(text: str) -> str:
"""
Strip ANSI escape codes from a string.
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index 539420e87..76a5774ab 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -1,10 +1,6 @@
import asyncio
-import io
-import os
-import tarfile
-from glob import glob
from types import TracebackType
-from typing import Callable, Literal, Optional, List
+from typing import Callable, Literal, Optional, List, Union
import httpx
@@ -26,7 +22,7 @@ from e2b.api.client.models import (
from e2b.exceptions import BuildException, FileUploadException
from e2b.template.logger import LogEntry
from e2b.template.types import TemplateType
-from e2b.template.utils import get_build_step_index
+from e2b.template.utils import get_build_step_index, tar_file_stream
async def request_build(
@@ -85,28 +81,14 @@ async def upload_file(
file_name: str,
context_path: str,
url: str,
+ ignore_patterns: List[str],
resolve_symlinks: bool,
stack_trace: Optional[TracebackType],
):
- tar_buffer = io.BytesIO()
-
try:
- 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:
- arcname = os.path.relpath(file, context_path)
- tar.add(file, arcname=arcname)
- except Exception as e:
- raise FileUploadException(f"Failed to create tar file: {e}").with_traceback(
- stack_trace
+ tar_buffer = tar_file_stream(
+ file_name, context_path, ignore_patterns, resolve_symlinks
)
-
- try:
async with httpx.AsyncClient() as client:
response = await client.put(url, content=tar_buffer.getvalue())
response.raise_for_status()
@@ -168,7 +150,7 @@ async def wait_for_build_finish(
build_id: str,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
logs_refresh_frequency: float = 0.2,
- stack_traces: List[TracebackType] = [],
+ stack_traces: List[Union[TracebackType, None]] = [],
):
logs_offset = 0
status: Literal["building", "waiting", "ready", "error"] = "building"
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index f759024c7..e9b7313d3 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -9,7 +9,7 @@ from e2b.template.consts import RESOLVE_SYMLINKS
from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
from e2b.template.types import BuildInfo, InstructionType
-
+from e2b.template.utils import read_dockerignore
from .build_api import (
get_build_status,
get_file_upload_link,
@@ -109,6 +109,10 @@ class AsyncTemplate(TemplateBase):
src,
template._template._file_context_path,
file_info.url,
+ [
+ *template._template._file_ignore_patterns,
+ *read_dockerignore(template._template._file_context_path),
+ ],
resolve_symlinks,
stack_trace,
)
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index f54efa516..116a1c922 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -1,10 +1,6 @@
-import io
-import os
-import tarfile
import time
-from glob import glob
from types import TracebackType
-from typing import Callable, Literal, Optional, List
+from typing import Callable, Literal, Optional, List, Union
import httpx
@@ -26,7 +22,7 @@ from e2b.api.client.models import (
from e2b.exceptions import BuildException, FileUploadException
from e2b.template.logger import LogEntry
from e2b.template.types import TemplateType
-from e2b.template.utils import get_build_step_index
+from e2b.template.utils import get_build_step_index, tar_file_stream
def request_build(
@@ -85,28 +81,14 @@ def upload_file(
file_name: str,
context_path: str,
url: str,
+ ignore_patterns: List[str],
resolve_symlinks: bool,
stack_trace: Optional[TracebackType],
):
- tar_buffer = io.BytesIO()
-
try:
- 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:
- arcname = os.path.relpath(file, context_path)
- tar.add(file, arcname=arcname)
- except Exception as e:
- raise FileUploadException(f"Failed to create tar file: {e}").with_traceback(
- stack_trace
+ tar_buffer = tar_file_stream(
+ file_name, context_path, ignore_patterns, resolve_symlinks
)
-
- try:
with httpx.Client() as client:
response = client.put(url, content=tar_buffer.getvalue())
response.raise_for_status()
@@ -168,7 +150,7 @@ def wait_for_build_finish(
build_id: str,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
logs_refresh_frequency: float = 0.2,
- stack_traces: List[TracebackType] = [],
+ stack_traces: List[Union[TracebackType, None]] = [],
):
logs_offset = 0
status: Literal["building", "waiting", "ready", "error"] = "building"
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index 8987118a4..77aa01e28 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -17,6 +17,7 @@ from e2b.template_sync.build_api import (
upload_file,
wait_for_build_finish,
)
+from e2b.template.utils import read_dockerignore
class Template(TemplateBase):
@@ -108,6 +109,10 @@ class Template(TemplateBase):
src,
template._template._file_context_path,
file_info.url,
+ [
+ *template._template._file_ignore_patterns,
+ *read_dockerignore(template._template._file_context_path),
+ ],
resolve_symlinks,
stack_trace,
)
diff --git a/packages/python-sdk/tests/async/template_async/utils/test_get_caller_directory.py b/packages/python-sdk/tests/async/template_async/utils/test_get_caller_directory.py
deleted file mode 100644
index b42f8b26b..000000000
--- a/packages/python-sdk/tests/async/template_async/utils/test_get_caller_directory.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import pytest
-from e2b.template.utils import get_caller_directory
-import os
-
-
-async def test_get_caller_directory():
- assert get_caller_directory(1) == os.path.dirname(__file__)
diff --git a/packages/python-sdk/tests/async/template_async/utils/test_get_all_files_for_files_hash.py b/packages/python-sdk/tests/shared/template/utils/get_all_files_in_path.py
similarity index 91%
rename from packages/python-sdk/tests/async/template_async/utils/test_get_all_files_for_files_hash.py
rename to packages/python-sdk/tests/shared/template/utils/get_all_files_in_path.py
index 20e781ccd..a55815a65 100644
--- a/packages/python-sdk/tests/async/template_async/utils/test_get_all_files_for_files_hash.py
+++ b/packages/python-sdk/tests/shared/template/utils/get_all_files_in_path.py
@@ -1,10 +1,10 @@
import os
import tempfile
import pytest
-from e2b.template.utils import get_all_files_for_files_hash
+from e2b.template.utils import get_all_files_in_path
-class TestGetAllFilesForFilesHash:
+class TestGetAllFilesInPath:
@pytest.fixture
def test_dir(self):
"""Create a temporary directory for testing."""
@@ -21,7 +21,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "file3.js"), "w") as f:
f.write("content3")
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
+ files = get_all_files_in_path("*.txt", test_dir, [])
assert len(files) == 2
assert any("file1.txt" in f for f in files)
@@ -43,7 +43,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "README.md"), "w") as f:
f.write("readme content")
- files = get_all_files_for_files_hash("src", test_dir, [])
+ files = get_all_files_in_path("src", test_dir, [])
assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
assert any("index.ts" in f for f in files)
@@ -63,7 +63,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "backup.txt"), "w") as f:
f.write("backup content")
- files = get_all_files_for_files_hash("*.txt", test_dir, ["temp*", "backup*"])
+ files = get_all_files_in_path("*.txt", test_dir, ["temp*", "backup*"])
assert len(files) == 2
assert any("file1.txt" in f for f in files)
@@ -93,9 +93,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "src", "utils", "helper.spec.ts"), "w") as f:
f.write("spec content")
- files = get_all_files_for_files_hash(
- "src", test_dir, ["**/*.test.*", "**/*.spec.*"]
- )
+ files = get_all_files_in_path("src", test_dir, ["**/*.test.*", "**/*.spec.*"])
assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
assert any("index.ts" in f for f in files)
@@ -110,7 +108,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "file.txt"), "w") as f:
f.write("content")
- files = get_all_files_for_files_hash("empty", test_dir, [])
+ files = get_all_files_in_path("empty", test_dir, [])
assert len(files) == 1
@@ -125,7 +123,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "file3.txt"), "w") as f:
f.write("content3")
- files = get_all_files_for_files_hash("*", test_dir, [])
+ files = get_all_files_in_path("*", test_dir, [])
assert len(files) == 4
assert any("file1.txt" in f for f in files)
@@ -147,7 +145,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "src", "components", "Button.css"), "w") as f:
f.write("css content")
- files = get_all_files_for_files_hash("src/**/*", test_dir, [])
+ files = get_all_files_in_path("src/**/*", test_dir, [])
assert len(files) == 6
assert any("index.ts" in f for f in files)
@@ -166,7 +164,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "file4.css"), "w") as f:
f.write("css content")
- files = get_all_files_for_files_hash("*.ts", test_dir, [])
+ files = get_all_files_in_path("*.ts", test_dir, [])
assert len(files) == 1
assert any("file1.ts" in f for f in files)
@@ -180,7 +178,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "banana.txt"), "w") as f:
f.write("b content")
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
+ files = get_all_files_in_path("*.txt", test_dir, [])
assert len(files) == 3
assert "apple.txt" in files[0]
@@ -192,7 +190,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "file.txt"), "w") as f:
f.write("content")
- files = get_all_files_for_files_hash("*.js", test_dir, [])
+ files = get_all_files_in_path("*.js", test_dir, [])
assert len(files) == 0
@@ -217,9 +215,7 @@ class TestGetAllFilesForFilesHash:
with open(os.path.join(test_dir, "README.md"), "w") as f:
f.write("readme content")
- files = get_all_files_for_files_hash(
- "src", test_dir, ["**/tests/**", "**/*.spec.*"]
- )
+ files = get_all_files_in_path("src", test_dir, ["**/tests/**", "**/*.spec.*"])
assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
assert any("index.ts" in f for f in files)
@@ -237,7 +233,7 @@ class TestGetAllFilesForFilesHash:
if hasattr(os, "symlink"):
os.symlink("original.txt", os.path.join(test_dir, "link.txt"))
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
+ files = get_all_files_in_path("*.txt", test_dir, [])
assert len(files) == 2
assert any("original.txt" in f for f in files)
@@ -267,7 +263,7 @@ class TestGetAllFilesForFilesHash:
) as f:
f.write("test content")
- files = get_all_files_for_files_hash("src", test_dir, ["**/ui/**"])
+ files = get_all_files_in_path("src", test_dir, ["**/ui/**"])
assert (
len(files) == 7
diff --git a/packages/python-sdk/tests/sync/template_sync/utils/test_get_caller_directory.py b/packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.py
similarity index 100%
rename from packages/python-sdk/tests/sync/template_sync/utils/test_get_caller_directory.py
rename to packages/python-sdk/tests/shared/template/utils/test_get_caller_directory.py
diff --git a/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py b/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py
new file mode 100644
index 000000000..8538dbced
--- /dev/null
+++ b/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py
@@ -0,0 +1,148 @@
+import os
+import tempfile
+import tarfile
+import io
+import pytest
+from e2b.template.utils import tar_file_stream
+
+
+class TestTarFileStream:
+ @pytest.fixture
+ def test_dir(self):
+ """Create a temporary directory for testing."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ yield tmpdir
+
+ def _extract_tar_contents(self, tar_buffer: io.BytesIO) -> dict:
+ """Extract tar contents into a dictionary mapping paths to file contents."""
+ tar_buffer.seek(0)
+ contents = {}
+ with tarfile.open(fileobj=tar_buffer, mode="r:gz") as tar:
+ for member in tar.getmembers():
+ if member.isfile():
+ file_obj = tar.extractfile(member)
+ if file_obj:
+ contents[member.name] = file_obj.read()
+ elif member.isdir():
+ contents[member.name] = None # Mark as directory
+ return contents
+
+ def test_should_create_tar_with_simple_files(self, test_dir):
+ """Test that function creates tar with simple files."""
+ # Create test files
+ file1_path = os.path.join(test_dir, "file1.txt")
+ file2_path = os.path.join(test_dir, "file2.txt")
+
+ with open(file1_path, "w") as f:
+ f.write("content1")
+ with open(file2_path, "w") as f:
+ f.write("content2")
+
+ tar_buffer = tar_file_stream("*.txt", test_dir, [], False)
+ contents = self._extract_tar_contents(tar_buffer)
+
+ assert len(contents) == 2
+ assert "file1.txt" in contents
+ assert "file2.txt" in contents
+ assert contents["file1.txt"] == b"content1"
+ assert contents["file2.txt"] == b"content2"
+
+ def test_should_respect_ignore_patterns(self, test_dir):
+ """Test that function respects ignore patterns."""
+ # Create test files
+ with open(os.path.join(test_dir, "file1.txt"), "w") as f:
+ f.write("content1")
+ with open(os.path.join(test_dir, "file2.txt"), "w") as f:
+ f.write("content2")
+ with open(os.path.join(test_dir, "temp.txt"), "w") as f:
+ f.write("temp content")
+ with open(os.path.join(test_dir, "backup.txt"), "w") as f:
+ f.write("backup content")
+
+ tar_buffer = tar_file_stream("*.txt", test_dir, ["temp*", "backup*"], False)
+ contents = self._extract_tar_contents(tar_buffer)
+
+ assert len(contents) == 2
+ assert "file1.txt" in contents
+ assert "file2.txt" in contents
+ assert contents["file1.txt"] == b"content1"
+ assert contents["file2.txt"] == b"content2"
+ assert "temp.txt" not in contents
+ assert "backup.txt" not in contents
+
+ def test_should_handle_nested_files(self, test_dir):
+ """Test that function handles nested directory structures."""
+ # Create nested directory structure
+ nested_dir = os.path.join(test_dir, "src", "components")
+ os.makedirs(nested_dir, exist_ok=True)
+
+ with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
+ f.write("index content")
+ with open(os.path.join(nested_dir, "Button.tsx"), "w") as f:
+ f.write("button content")
+
+ tar_buffer = tar_file_stream("src", test_dir, [], False)
+ contents = self._extract_tar_contents(tar_buffer)
+
+ # Should include the directory and files
+ assert "src" in contents or any("src" in name for name in contents.keys())
+ assert any("index.ts" in name for name in contents.keys())
+ assert any("Button.tsx" in name for name in contents.keys())
+
+ def test_should_resolve_symlinks_when_enabled(self, test_dir):
+ """Test that function resolves symlinks when resolve_symlinks=True."""
+ if not hasattr(os, "symlink"):
+ pytest.skip("Symlinks not supported on this platform")
+
+ # Create original file
+ original_path = os.path.join(test_dir, "original.txt")
+ with open(original_path, "w") as f:
+ f.write("original content")
+
+ # Create symlink
+ symlink_path = os.path.join(test_dir, "link.txt")
+ os.symlink("original.txt", symlink_path)
+
+ # Test with resolve_symlinks=True
+ tar_buffer = tar_file_stream("*.txt", test_dir, [], True)
+ contents = self._extract_tar_contents(tar_buffer)
+
+ # Both files should be in tar
+ assert "original.txt" in contents
+ assert "link.txt" in contents
+ # Symlink should be resolved (contain actual content, not link)
+ assert contents["original.txt"] == b"original content"
+ assert contents["link.txt"] == b"original content"
+
+ def test_should_preserve_symlinks_when_disabled(self, test_dir):
+ """Test that function preserves symlinks when resolve_symlinks=False."""
+ if not hasattr(os, "symlink"):
+ pytest.skip("Symlinks not supported on this platform")
+
+ # Create original file
+ original_path = os.path.join(test_dir, "original.txt")
+ with open(original_path, "w") as f:
+ f.write("original content")
+
+ # Create symlink
+ symlink_path = os.path.join(test_dir, "link.txt")
+ os.symlink("original.txt", symlink_path)
+
+ # Test with resolve_symlinks=False
+ tar_buffer = tar_file_stream("*.txt", test_dir, [], False)
+ tar_buffer.seek(0)
+
+ with tarfile.open(fileobj=tar_buffer, mode="r:gz") as tar:
+ members = {m.name: m for m in tar.getmembers()}
+
+ # Both files should be in tar
+ assert "original.txt" in members
+ assert "link.txt" in members
+
+ # Original should be a regular file
+ assert members["original.txt"].isfile()
+ assert not members["original.txt"].issym()
+
+ # Link should be a symlink
+ assert members["link.txt"].issym()
+ assert members["link.txt"].linkname == "original.txt"
diff --git a/packages/python-sdk/tests/sync/template_sync/utils/test_get_all_files_for_files_hash.py b/packages/python-sdk/tests/sync/template_sync/utils/test_get_all_files_for_files_hash.py
deleted file mode 100644
index 20e781ccd..000000000
--- a/packages/python-sdk/tests/sync/template_sync/utils/test_get_all_files_for_files_hash.py
+++ /dev/null
@@ -1,279 +0,0 @@
-import os
-import tempfile
-import pytest
-from e2b.template.utils import get_all_files_for_files_hash
-
-
-class TestGetAllFilesForFilesHash:
- @pytest.fixture
- def test_dir(self):
- """Create a temporary directory for testing."""
- with tempfile.TemporaryDirectory() as tmpdir:
- yield tmpdir
-
- def test_should_return_files_matching_simple_pattern(self, test_dir):
- """Test that function returns files matching a simple pattern."""
- # Create test files
- with open(os.path.join(test_dir, "file1.txt"), "w") as f:
- f.write("content1")
- with open(os.path.join(test_dir, "file2.txt"), "w") as f:
- f.write("content2")
- with open(os.path.join(test_dir, "file3.js"), "w") as f:
- f.write("content3")
-
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
-
- assert len(files) == 2
- assert any("file1.txt" in f for f in files)
- assert any("file2.txt" in f for f in files)
- assert not any("file3.js" in f for f in files)
-
- def test_should_handle_directory_patterns_recursively(self, test_dir):
- """Test that function handles directory patterns recursively."""
- # Create nested directory structure
- os.makedirs(os.path.join(test_dir, "src", "components"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "utils"), exist_ok=True)
-
- with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
- f.write("index content")
- with open(os.path.join(test_dir, "src", "components", "Button.tsx"), "w") as f:
- f.write("button content")
- with open(os.path.join(test_dir, "src", "utils", "helper.ts"), "w") as f:
- f.write("helper content")
- with open(os.path.join(test_dir, "README.md"), "w") as f:
- f.write("readme content")
-
- files = get_all_files_for_files_hash("src", test_dir, [])
-
- assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
- assert any("index.ts" in f for f in files)
- assert any("Button.tsx" in f for f in files)
- assert any("helper.ts" in f for f in files)
- assert not any("README.md" in f for f in files)
-
- def test_should_respect_ignore_patterns(self, test_dir):
- """Test that function respects ignore patterns."""
- # Create test files
- with open(os.path.join(test_dir, "file1.txt"), "w") as f:
- f.write("content1")
- with open(os.path.join(test_dir, "file2.txt"), "w") as f:
- f.write("content2")
- with open(os.path.join(test_dir, "temp.txt"), "w") as f:
- f.write("temp content")
- with open(os.path.join(test_dir, "backup.txt"), "w") as f:
- f.write("backup content")
-
- files = get_all_files_for_files_hash("*.txt", test_dir, ["temp*", "backup*"])
-
- assert len(files) == 2
- assert any("file1.txt" in f for f in files)
- assert any("file2.txt" in f for f in files)
- assert not any("temp.txt" in f for f in files)
- assert not any("backup.txt" in f for f in files)
-
- def test_should_handle_complex_ignore_patterns(self, test_dir):
- """Test that function handles complex ignore patterns."""
- # Create nested structure with various file types
- os.makedirs(os.path.join(test_dir, "src", "components"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "utils"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "tests"), exist_ok=True)
-
- with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
- f.write("index content")
- with open(os.path.join(test_dir, "src", "components", "Button.tsx"), "w") as f:
- f.write("button content")
- with open(os.path.join(test_dir, "src", "utils", "helper.ts"), "w") as f:
- f.write("helper content")
- with open(os.path.join(test_dir, "tests", "test.spec.ts"), "w") as f:
- f.write("test content")
- with open(
- os.path.join(test_dir, "src", "components", "Button.test.tsx"), "w"
- ) as f:
- f.write("test content")
- with open(os.path.join(test_dir, "src", "utils", "helper.spec.ts"), "w") as f:
- f.write("spec content")
-
- files = get_all_files_for_files_hash(
- "src", test_dir, ["**/*.test.*", "**/*.spec.*"]
- )
-
- assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
- assert any("index.ts" in f for f in files)
- assert any("Button.tsx" in f for f in files)
- assert any("helper.ts" in f for f in files)
- assert not any("Button.test.tsx" in f for f in files)
- assert not any("helper.spec.ts" in f for f in files)
-
- def test_should_handle_empty_directories(self, test_dir):
- """Test that function handles empty directories."""
- os.makedirs(os.path.join(test_dir, "empty"), exist_ok=True)
- with open(os.path.join(test_dir, "file.txt"), "w") as f:
- f.write("content")
-
- files = get_all_files_for_files_hash("empty", test_dir, [])
-
- assert len(files) == 1
-
- def test_should_handle_mixed_files_and_directories(self, test_dir):
- """Test that function handles mixed files and directories."""
- # Create a mix of files and directories
- with open(os.path.join(test_dir, "file1.txt"), "w") as f:
- f.write("content1")
- os.makedirs(os.path.join(test_dir, "dir1"), exist_ok=True)
- with open(os.path.join(test_dir, "dir1", "file2.txt"), "w") as f:
- f.write("content2")
- with open(os.path.join(test_dir, "file3.txt"), "w") as f:
- f.write("content3")
-
- files = get_all_files_for_files_hash("*", test_dir, [])
-
- assert len(files) == 4
- assert any("file1.txt" in f for f in files)
- assert any("file2.txt" in f for f in files)
- assert any("file3.txt" in f for f in files)
-
- def test_should_handle_glob_patterns_with_subdirectories(self, test_dir):
- """Test that function handles glob patterns with subdirectories."""
- # Create nested structure
- os.makedirs(os.path.join(test_dir, "src", "components"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "utils"), exist_ok=True)
-
- with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
- f.write("index content")
- with open(os.path.join(test_dir, "src", "components", "Button.tsx"), "w") as f:
- f.write("button content")
- with open(os.path.join(test_dir, "src", "utils", "helper.ts"), "w") as f:
- f.write("helper content")
- with open(os.path.join(test_dir, "src", "components", "Button.css"), "w") as f:
- f.write("css content")
-
- files = get_all_files_for_files_hash("src/**/*", test_dir, [])
-
- assert len(files) == 6
- assert any("index.ts" in f for f in files)
- assert any("Button.tsx" in f for f in files)
- assert any("helper.ts" in f for f in files)
- assert any("Button.css" in f for f in files)
-
- def test_should_handle_specific_file_extensions(self, test_dir):
- """Test that function handles specific file extensions."""
- with open(os.path.join(test_dir, "file1.ts"), "w") as f:
- f.write("ts content")
- with open(os.path.join(test_dir, "file2.js"), "w") as f:
- f.write("js content")
- with open(os.path.join(test_dir, "file3.tsx"), "w") as f:
- f.write("tsx content")
- with open(os.path.join(test_dir, "file4.css"), "w") as f:
- f.write("css content")
-
- files = get_all_files_for_files_hash("*.ts", test_dir, [])
-
- assert len(files) == 1
- assert any("file1.ts" in f for f in files)
-
- def test_should_return_sorted_files(self, test_dir):
- """Test that function returns sorted files."""
- with open(os.path.join(test_dir, "zebra.txt"), "w") as f:
- f.write("z content")
- with open(os.path.join(test_dir, "apple.txt"), "w") as f:
- f.write("a content")
- with open(os.path.join(test_dir, "banana.txt"), "w") as f:
- f.write("b content")
-
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
-
- assert len(files) == 3
- assert "apple.txt" in files[0]
- assert "banana.txt" in files[1]
- assert "zebra.txt" in files[2]
-
- def test_should_handle_no_matching_files(self, test_dir):
- """Test that function handles no matching files."""
- with open(os.path.join(test_dir, "file.txt"), "w") as f:
- f.write("content")
-
- files = get_all_files_for_files_hash("*.js", test_dir, [])
-
- assert len(files) == 0
-
- def test_should_handle_complex_ignore_patterns_with_directories(self, test_dir):
- """Test that function handles complex ignore patterns with directories."""
- # Create a complex structure
- os.makedirs(os.path.join(test_dir, "src", "components"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "utils"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "tests"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "dist"), exist_ok=True)
-
- with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
- f.write("index content")
- with open(os.path.join(test_dir, "src", "components", "Button.tsx"), "w") as f:
- f.write("button content")
- with open(os.path.join(test_dir, "src", "utils", "helper.ts"), "w") as f:
- f.write("helper content")
- with open(os.path.join(test_dir, "src", "tests", "test.spec.ts"), "w") as f:
- f.write("test content")
- with open(os.path.join(test_dir, "dist", "bundle.js"), "w") as f:
- f.write("bundle content")
- with open(os.path.join(test_dir, "README.md"), "w") as f:
- f.write("readme content")
-
- files = get_all_files_for_files_hash(
- "src", test_dir, ["**/tests/**", "**/*.spec.*"]
- )
-
- assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
- assert any("index.ts" in f for f in files)
- assert any("Button.tsx" in f for f in files)
- assert any("helper.ts" in f for f in files)
- assert not any("test.spec.ts" in f for f in files)
-
- def test_should_handle_symlinks(self, test_dir):
- """Test that function handles symbolic links."""
- # Create a file and a symlink to it
- with open(os.path.join(test_dir, "original.txt"), "w") as f:
- f.write("original content")
-
- # Create symlink (only on Unix-like systems)
- if hasattr(os, "symlink"):
- os.symlink("original.txt", os.path.join(test_dir, "link.txt"))
-
- files = get_all_files_for_files_hash("*.txt", test_dir, [])
-
- assert len(files) == 2
- assert any("original.txt" in f for f in files)
- assert any("link.txt" in f for f in files)
-
- def test_should_handle_nested_ignore_patterns(self, test_dir):
- """Test that function handles nested ignore patterns."""
- # Create nested structure
- os.makedirs(os.path.join(test_dir, "src", "components", "ui"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "components", "forms"), exist_ok=True)
- os.makedirs(os.path.join(test_dir, "src", "utils"), exist_ok=True)
-
- with open(os.path.join(test_dir, "src", "index.ts"), "w") as f:
- f.write("index content")
- with open(
- os.path.join(test_dir, "src", "components", "ui", "Button.tsx"), "w"
- ) as f:
- f.write("button content")
- with open(
- os.path.join(test_dir, "src", "components", "forms", "Input.tsx"), "w"
- ) as f:
- f.write("input content")
- with open(os.path.join(test_dir, "src", "utils", "helper.ts"), "w") as f:
- f.write("helper content")
- with open(
- os.path.join(test_dir, "src", "components", "ui", "Button.test.tsx"), "w"
- ) as f:
- f.write("test content")
-
- files = get_all_files_for_files_hash("src", test_dir, ["**/ui/**"])
-
- assert (
- len(files) == 7
- ) # 3 files + 4 directories (src, components, forms, utils)
- assert any("index.ts" in f for f in files)
- assert any("Input.tsx" in f for f in files)
- assert any("helper.ts" in f for f in files)
- assert not any("Button.tsx" in f for f in files)
- assert not any("Button.test.tsx" in f for f in files)