Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(sdk): apply .dockerignore patterns Docker-style when copying template files (#1917)

devin-ai-integration[bot]03887ad7813a
diff --git a/.changeset/dockerignore-semantics.md b/.changeset/dockerignore-semantics.md
new file mode 100644
index 000000000..f11668e60
--- /dev/null
+++ b/.changeset/dockerignore-semantics.md
@@ -0,0 +1,17 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Apply `.dockerignore` and `fileIgnorePatterns` / `file_ignore_patterns` the way Docker does when copying files into a template, so ignored files are no longer uploaded or included in the files hash:
+
+- A pattern that matches a directory (`node_modules`, `.git`, `dist/`) now excludes everything under it, and a leading `/` is ignored.
+- `!` patterns re-include paths; the last matching pattern wins.
+- In Python, patterns now also apply when the copied path contains `.` or `..` segments (for example `copy(".")`).
+- `fileIgnorePatterns` / `file_ignore_patterns` are applied after the `.dockerignore` lines, so they take precedence.
+- Absolute patterns pointing into the context directory are treated as relative to it.
+- Brace expansion (`{a,b}`) is not supported, as in Docker. In JS, `fileIgnorePatterns` such as `**/*.{env,pem}` previously expanded and now match `{env,pem}` literally; list each pattern separately instead (`**/*.env`, `**/*.pem`).
+- In Python, copying a symlink to a directory copies the link itself instead of the directory's contents, as in JS.
+- Copying a path inside an ignored directory now fails with "No files found", as in Docker. An invalid pattern (such as an unterminated `[`) now raises an error.
+
+Directory sizes are no longer part of the files hash, since they depend on the filesystem rather than on the copied files. The files hash of `copy()` steps that copy directories or are affected by ignore patterns changes once, so those steps are rebuilt on the next build.
diff --git a/packages/js-sdk/src/template/dockerignore.ts b/packages/js-sdk/src/template/dockerignore.ts
new file mode 100644
index 000000000..7bb99f014
--- /dev/null
+++ b/packages/js-sdk/src/template/dockerignore.ts
@@ -0,0 +1,193 @@
+/**
+ * Matching of `.dockerignore` patterns, following the semantics Docker uses to
+ * filter the build context.
+ *
+ * Port of the pattern matcher from moby/patternmatcher (Apache-2.0):
+ * https://github.com/moby/patternmatcher
+ */
+import path from 'node:path'
+import { TemplateError } from '../errors'
+
+// Characters that have a meaning in a regex but not in a Docker pattern
+const LITERAL_REGEX_CHARS = new Set([
+ '.',
+ '+',
+ '(',
+ ')',
+ '|',
+ '{',
+ '}',
+ '$',
+ '^',
+])
+const WILDCARD_CHARS = /[*?[\\]/
+// Evaluated lazily, as `node:path` is not available when loaded in the browser
+const backslashIsSeparator = () => path.sep === '\\'
+
+function escapeRegex(ch: string): string {
+ return ch.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&')
+}
+
+// Equivalent of Go's filepath.Clean followed by filepath.ToSlash
+function clean(pattern: string): string {
+ if (backslashIsSeparator()) {
+ pattern = pattern.replace(/\\/g, '/')
+ }
+ return path.posix.normalize(pattern).replace(/(.)\/$/, '$1')
+}
+
+function compile(pattern: string): RegExp {
+ let regex = '^'
+ const n = pattern.length
+ const backslashIsEscape = !backslashIsSeparator()
+ let i = 0
+ while (i < n) {
+ const ch = pattern[i++]
+ if (ch === '*') {
+ if (pattern[i] === '*') {
+ i++
+ // Treat "**/" as "**"
+ if (pattern[i] === '/') {
+ i++
+ }
+ regex += i >= n ? '.*' : '(.*/)?'
+ } else {
+ regex += '[^/]*'
+ }
+ } else if (ch === '?') {
+ regex += '[^/]'
+ } else if (ch === '[') {
+ // Copy a bracket expression as is, a leading "^" negates it
+ let j = i
+ if (pattern[j] === '^') {
+ j++
+ }
+ while (j < n && pattern[j] !== ']') {
+ if (pattern[j] === '\\' && backslashIsEscape) {
+ j++
+ }
+ j++
+ }
+ regex += pattern.slice(i - 1, j + 1)
+ i = j + 1
+ } else if (LITERAL_REGEX_CHARS.has(ch)) {
+ regex += '\\' + ch
+ } else if (ch === '\\' && backslashIsEscape) {
+ // Escape the next character
+ if (i < n) {
+ regex += escapeRegex(pattern[i++])
+ } else {
+ regex += '\\\\'
+ }
+ } else {
+ regex += ch
+ }
+ }
+ return new RegExp(regex + '$')
+}
+
+interface Pattern {
+ exclusion: boolean
+ dirs: string[]
+ regex: RegExp
+}
+
+/**
+ * Match paths relative to the context root against `.dockerignore` patterns.
+ *
+ * A pattern that matches a directory excludes everything under it, a leading
+ * `/` is ignored, and `!` patterns re-include paths (the last matching
+ * pattern wins).
+ */
+export class PatternMatcher {
+ private readonly patterns: Pattern[] = []
+
+ constructor(patterns: string[]) {
+ for (const original of patterns) {
+ let pattern = original.trim()
+ if (!pattern || pattern.startsWith('#')) {
+ continue
+ }
+ const exclusion = pattern.startsWith('!')
+ if (exclusion) {
+ pattern = pattern.slice(1).trim()
+ if (!pattern) {
+ continue
+ }
+ }
+ pattern = clean(pattern)
+ if (pattern.length > 1 && pattern.startsWith('/')) {
+ pattern = pattern.slice(1)
+ }
+ let regex: RegExp
+ try {
+ regex = compile(pattern)
+ } catch (err) {
+ throw new TemplateError(
+ `Invalid ignore pattern '${original}': ${(err as Error).message}`
+ )
+ }
+ this.patterns.push({ exclusion, dirs: pattern.split('/'), regex })
+ }
+ }
+
+ /**
+ * Whether the path or one of its parent directories is excluded.
+ *
+ * @param p Slash-separated path relative to the context root
+ * @returns True if the path is excluded
+ */
+ matches(p: string): boolean {
+ const parentPath = path.posix.dirname(p)
+ const parentDirs = parentPath === '.' ? [] : parentPath.split('/')
+
+ let matched = false
+ for (const pattern of this.patterns) {
+ // An inclusion can't change an already matched path, and an
+ // exclusion can't change a path that hasn't matched yet
+ if (pattern.exclusion !== matched) {
+ continue
+ }
+ const match =
+ pattern.regex.test(p) ||
+ parentDirs.some((_, i) =>
+ pattern.regex.test(parentDirs.slice(0, i + 1).join('/'))
+ )
+ if (match) {
+ matched = !pattern.exclusion
+ }
+ }
+ return matched
+ }
+
+ /**
+ * Whether a `!` pattern could re-include a path under the directory,
+ * in which case an excluded directory must still be walked.
+ *
+ * @param dirPath Slash-separated directory path relative to the context root
+ * @returns True if a path under the directory could be re-included
+ */
+ mayMatchUnder(dirPath: string): boolean {
+ const dirSegments = dirPath.split('/')
+ return this.patterns.some(
+ (pattern) =>
+ pattern.exclusion && patternMayMatchUnder(pattern, dirSegments)
+ )
+ }
+}
+
+function patternMayMatchUnder(pattern: Pattern, dirSegments: string[]) {
+ for (let i = 0; i < dirSegments.length; i++) {
+ if (i >= pattern.dirs.length) {
+ return false
+ }
+ const segment = pattern.dirs[i]
+ if (segment.includes('**')) {
+ return true
+ }
+ if (!WILDCARD_CHARS.test(segment) && segment !== dirSegments[i]) {
+ return false
+ }
+ }
+ return pattern.dirs.length > dirSegments.length
+}
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 39074514d..b54182fbc 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -1133,8 +1133,8 @@ export class TemplateBase
url,
headers,
ignorePatterns: [
- ...this.fileIgnorePatterns,
...readDockerignore(this.fileContextPath.toString()),
+ ...this.fileIgnorePatterns,
],
resolveSymlinks: instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
gzip: instruction.gzip ?? GZIP,
@@ -1224,10 +1224,10 @@ export class TemplateBase
dest,
this.fileContextPath.toString(),
[
- ...this.fileIgnorePatterns,
...(runtime === 'browser'
? []
: readDockerignore(this.fileContextPath.toString())),
+ ...this.fileIgnorePatterns,
],
instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
stackTrace
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index 654575b5d..cbd790195 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -14,7 +14,10 @@ export type TemplateOptions = {
*/
fileContextPath?: PathLike
/**
- * Array of glob patterns to ignore when copying files.
+ * Patterns in `.dockerignore` syntax for files to exclude when copying.
+ * They are applied after the `.dockerignore` file in the context directory, so they take precedence over it.
+ * An invalid pattern (such as an unterminated `[`) throws a `TemplateError`.
+ * Brace expansion (`{a,b}`) is not supported, as in Docker.
*/
fileIgnorePatterns?: string[]
}
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index 868c38949..8504af5fa 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -7,7 +7,8 @@ import { parse, type StackFrame } from 'error-stack-parser-es'
import { dynamicImport } from '../utils'
import { TemplateError } from '../errors'
import { BASE_STEP_NAME, FINALIZE_STEP_NAME } from './consts'
-import type { Path } from 'glob'
+import { PatternMatcher } from './dockerignore'
+import type { IgnoreLike, Path } from 'glob'
import type { BuildOptions } from './types'
/**
@@ -112,7 +113,9 @@ export function readDockerignore(contextPath: string): string[] {
return []
}
- const content = fs.readFileSync(dockerignorePath, 'utf-8')
+ const content = fs
+ .readFileSync(dockerignorePath, 'utf-8')
+ .replace(/^\uFEFF/, '')
return content
.split('\n')
.map((line) => line.trim())
@@ -128,12 +131,67 @@ function normalizePath(path: string): string {
return path.replace(/\\/g, '/')
}
+function normalizeIgnorePattern(pattern: string, contextPath: string): string {
+ let trimmed = pattern.trim()
+ const negated = trimmed.startsWith('!')
+ if (negated) {
+ trimmed = trimmed.slice(1).trim()
+ }
+ // Absolute patterns pointing into the context are made relative to it.
+ // Other patterns are anchored at the context root, a leading `/` is ignored.
+ if (path.isAbsolute(trimmed)) {
+ const relative = path.relative(contextPath, trimmed)
+ if (
+ relative !== '' &&
+ relative !== '..' &&
+ !relative.startsWith(`..${path.sep}`) &&
+ !path.isAbsolute(relative)
+ ) {
+ trimmed = relative
+ }
+ }
+ return (negated ? '!' : '') + trimmed
+}
+
+/**
+ * Create a glob `ignore` matcher that follows `.dockerignore` semantics:
+ * patterns are relative to the context root, a pattern matching a directory
+ * excludes everything under it, and `!` patterns re-include paths
+ * (the last matching pattern wins). The context root is never excluded.
+ *
+ * @param ignorePatterns Ignore patterns in `.dockerignore` syntax
+ * @param contextPath Base directory the patterns are relative to
+ * @returns Matcher to pass as the glob `ignore` option
+ */
+function createIgnoreMatcher(
+ ignorePatterns: string[],
+ contextPath: string
+): IgnoreLike {
+ const absoluteContextPath = path.resolve(contextPath)
+ const matcher = new PatternMatcher(
+ ignorePatterns.map((pattern) =>
+ normalizeIgnorePattern(pattern, absoluteContextPath)
+ )
+ )
+
+ const ignored = (p: Path) => {
+ const relativePath = p.relativePosix()
+ return relativePath !== '' && matcher.matches(relativePath)
+ }
+
+ return {
+ ignored,
+ childrenIgnored: (p) =>
+ ignored(p) && !matcher.mayMatchUnder(p.relativePosix()),
+ }
+}
+
/**
* Get all files for a given path and ignore patterns.
*
* @param src Path to the source directory
* @param contextPath Base directory for resolving relative paths
- * @param ignorePatterns Ignore patterns
+ * @param ignorePatterns Ignore patterns in `.dockerignore` syntax
* @returns Array of files
*/
export async function getAllFilesInPath(
@@ -144,17 +202,45 @@ export async function getAllFilesInPath(
) {
const { glob } = await dynamicImport<typeof import('glob')>('glob')
const files = new Map<string, Path>()
+ const ignore = createIgnoreMatcher(ignorePatterns, contextPath)
const globFiles = await glob(src, {
- ignore: ignorePatterns,
+ ignore,
withFileTypes: true,
dot: true,
- // this is required so that the ignore pattern is relative to the file path
cwd: contextPath,
})
+ // Visit parents before their children, so paths under an already walked
+ // directory are not walked again
+ const depth = (p: Path) => {
+ const relativePath = p.relativePosix()
+ return relativePath === '' ? 0 : relativePath.split('/').length
+ }
+ globFiles.sort((a, b) => depth(a) - depth(b))
+ const walkedDirs = new Set<string>()
+ const isUnderWalkedDir = (relativePath: string) => {
+ if (walkedDirs.has('')) {
+ return true
+ }
+ for (
+ let parent = path.posix.dirname(relativePath);
+ parent !== '.' && parent !== '/';
+ parent = path.posix.dirname(parent)
+ ) {
+ if (walkedDirs.has(parent)) {
+ return true
+ }
+ }
+ return false
+ }
+
for (const file of globFiles) {
+ if (isUnderWalkedDir(file.relativePosix())) {
+ continue
+ }
if (file.isDirectory()) {
+ walkedDirs.add(file.relativePosix())
// For directories, add the directory itself and all files inside it
if (includeDirectories) {
files.set(file.fullpath(), file)
@@ -166,7 +252,7 @@ export async function getAllFilesInPath(
path.join(file.relative() || '.', '**/*')
)
const dirFiles = await glob(dirPattern, {
- ignore: ignorePatterns,
+ ignore,
withFileTypes: true,
dot: true,
cwd: contextPath,
@@ -194,7 +280,7 @@ export async function getAllFilesInPath(
* @param src Source path pattern for files to copy
* @param dest Destination path where files will be copied
* @param contextPath Base directory for resolving relative paths
- * @param ignorePatterns Glob patterns to ignore
+ * @param ignorePatterns Ignore patterns in `.dockerignore` syntax
* @param resolveSymlinks Whether to resolve symbolic links when hashing
* @param stackTrace Optional stack trace for error reporting
* @returns Hex string hash of all files
@@ -228,7 +314,10 @@ export async function calculateFilesHash(
// Exclude uid, gid, and mtime to ensure consistent hashes across environments
const hashStats = (stats: fs.Stats) => {
hash.update(stats.mode.toString())
- hash.update(stats.size.toString())
+ // A directory's size depends on the filesystem, not on the copied files
+ if (!stats.isDirectory()) {
+ hash.update(stats.size.toString())
+ }
}
// Process files recursively
diff --git a/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
index 30d888fde..b5b8c6e54 100644
--- a/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
+++ b/packages/js-sdk/tests/template/utils/getAllFilesInPath.test.ts
@@ -1,8 +1,12 @@
import { expect, test, describe, beforeAll, afterAll, beforeEach } from 'vitest'
-import { writeFile, mkdir, mkdtemp, rm } from 'fs/promises'
+import { appendFile, writeFile, mkdir, mkdtemp, rm, symlink } from 'fs/promises'
import { tmpdir } from 'os'
-import { join, basename } from 'path'
-import { getAllFilesInPath } from '../../../src/template/utils'
+import { join, basename, relative } from 'path'
+import {
+ calculateFilesHash,
+ getAllFilesInPath,
+ readDockerignore,
+} from '../../../src/template/utils'
describe('getAllFilesInPath', () => {
// A temp directory, so a test run never writes into the repository tree.
@@ -320,10 +324,192 @@ describe('getAllFilesInPath', () => {
'**/*.spec.*',
])
- expect(files).toHaveLength(6) // 3 files + 3 directories (src, components, utils)
+ // 3 files + 4 directories (src, components, utils and the emptied tests,
+ // since `tests/**` matches the contents of `tests`, as in Docker)
+ expect(files).toHaveLength(7)
expect(files.some((f) => f.fullpath().endsWith('index.ts'))).toBe(true)
expect(files.some((f) => f.fullpath().endsWith('Button.tsx'))).toBe(true)
expect(files.some((f) => f.fullpath().endsWith('helper.ts'))).toBe(true)
expect(files.some((f) => f.fullpath().endsWith('test.spec.ts'))).toBe(false)
})
+
+ describe('.dockerignore semantics', () => {
+ const relativePaths = async (src: string, ignorePatterns: string[]) =>
+ (await getAllFilesInPath(src, testDir, ignorePatterns))
+ .map((f) => relative(testDir, f.fullpath()).replace(/\\/g, '/') || '.')
+ .sort()
+
+ beforeEach(async () => {
+ await mkdir(join(testDir, 'node_modules', 'pkg'), { recursive: true })
+ await mkdir(join(testDir, 'src', 'generated'), { recursive: true })
+ await mkdir(join(testDir, 'src', 'node_modules'), { recursive: true })
+ await mkdir(join(testDir, '.git'), { recursive: true })
+ await writeFile(join(testDir, '.env'), 'SECRET=1')
+ await writeFile(join(testDir, 'node_modules', 'pkg', 'index.js'), 'x')
+ await writeFile(join(testDir, 'src', 'app.ts'), 'x')
+ await writeFile(join(testDir, 'src', 'app.spec.ts'), 'x')
+ await writeFile(join(testDir, 'src', 'generated', 'api.ts'), 'x')
+ await writeFile(join(testDir, 'src', 'node_modules', 'lib.js'), 'x')
+ await writeFile(join(testDir, '.git', 'HEAD'), 'ref')
+ })
+
+ const patterns = [
+ '.env',
+ 'node_modules',
+ '.git',
+ '**/*.spec.*',
+ 'src/generated',
+ ]
+
+ test.each(['.', './', './src', 'src', 'src/.', 'src/../src'])(
+ 'should exclude ignored directories with their contents for %s',
+ async (src) => {
+ const files = await relativePaths(src, patterns)
+ const expected = [
+ 'src',
+ 'src/app.ts',
+ 'src/node_modules',
+ 'src/node_modules/lib.js',
+ ]
+ const copiesRoot = src === '.' || src === './'
+ expect(files).toEqual(copiesRoot ? ['.', ...expected] : expected)
+ }
+ )
+
+ test('should ignore a leading slash and a trailing slash', async () => {
+ const files = await relativePaths('.', [
+ '/node_modules',
+ '/.git/',
+ 'src/',
+ ])
+ expect(files).toEqual(['.', '.env'])
+ })
+
+ test('should never exclude the context root', async () => {
+ const files = await relativePaths('.', ['.', '.*', 'src', 'node_modules'])
+ expect(files).toEqual(['.'])
+ })
+
+ test('should not copy paths inside an ignored directory', async () => {
+ const files = await relativePaths('node_modules/pkg', ['node_modules'])
+ expect(files).toEqual([])
+ })
+
+ test('should re-include paths matched by a negated pattern', async () => {
+ const files = await relativePaths('.', [
+ '*',
+ '!src',
+ 'src/generated',
+ '!node_modules/pkg/index.js',
+ ])
+ expect(files).toEqual([
+ '.',
+ 'node_modules/pkg/index.js',
+ 'src',
+ 'src/app.spec.ts',
+ 'src/app.ts',
+ 'src/node_modules',
+ 'src/node_modules/lib.js',
+ ])
+ })
+
+ test('should make absolute patterns inside the context relative', async () => {
+ const files = await relativePaths('.', [
+ join(testDir, 'src'),
+ join(testDir, 'node_modules', '**'),
+ '.git',
+ ])
+ expect(files).toEqual(['.', '.env', 'node_modules'])
+ })
+
+ test('should match regex special characters literally', async () => {
+ await writeFile(join(testDir, 'file (1).txt'), 'x')
+ await writeFile(join(testDir, 'c++'), 'x')
+ await writeFile(join(testDir, 'a'), 'x')
+ const files = await relativePaths('*', ['file (1).txt', 'c++', 'a|b'])
+ expect(files).not.toContain('file (1).txt')
+ expect(files).not.toContain('c++')
+ expect(files).toContain('a')
+ })
+
+ test('should throw on an invalid pattern', async () => {
+ await expect(getAllFilesInPath('.', testDir, ['[abc'])).rejects.toThrow(
+ "Invalid ignore pattern '[abc'"
+ )
+ })
+
+ test('should keep the files hash stable when ignored files change', async () => {
+ const hash = () =>
+ calculateFilesHash('.', '/app', testDir, ['.git'], false, undefined)
+ const before = await hash()
+ await appendFile(join(testDir, '.git', 'HEAD'), 'x')
+ expect(await hash()).toBe(before)
+ })
+
+ test('should match a caret literally outside a bracket expression', async () => {
+ for (const name of ['report^draft.txt', 'ax', 'bx']) {
+ await writeFile(join(testDir, name), 'x')
+ }
+ const files = await relativePaths('*', ['report^draft.txt', '[^a]x'])
+ expect(files).not.toContain('report^draft.txt')
+ expect(files).not.toContain('bx')
+ expect(files).toContain('ax')
+ })
+
+ test('should not walk the recursive matches of a directory again', async () => {
+ const files = await relativePaths('**/*', patterns)
+ expect(files).toEqual([
+ 'src',
+ 'src/app.ts',
+ 'src/node_modules',
+ 'src/node_modules/lib.js',
+ ])
+ })
+
+ test.skipIf(process.platform === 'win32')(
+ 'should copy a symlink to a directory without its contents',
+ async () => {
+ await mkdir(join(testDir, 'real'))
+ await writeFile(join(testDir, 'real', 'secret.txt'), 'x')
+ await symlink('real', join(testDir, 'linked'))
+ expect(await relativePaths('linked', [])).toEqual(['linked'])
+ }
+ )
+
+ test('should keep the files hash stable when ignored files grow a directory', async () => {
+ const hash = () =>
+ calculateFilesHash(
+ '.',
+ '/app',
+ testDir,
+ ['node_modules/*'],
+ false,
+ undefined
+ )
+ const before = await hash()
+ for (let i = 0; i < 300; i++) {
+ await writeFile(
+ join(testDir, 'node_modules', `ignored-file-with-a-long-name-${i}`),
+ 'x'
+ )
+ }
+ expect(await hash()).toBe(before)
+ })
+
+ test('should not expand braces', async () => {
+ await writeFile(join(testDir, 'a.txt'), 'x')
+ await writeFile(join(testDir, 'b.{txt,md}'), 'x')
+ const files = await relativePaths('*', ['*.{txt,md}'])
+ expect(files).toContain('a.txt')
+ expect(files).not.toContain('b.{txt,md}')
+ })
+
+ test('should strip a UTF-8 BOM from .dockerignore', async () => {
+ await writeFile(
+ join(testDir, '.dockerignore'),
+ '\uFEFF.env\n# comment\n\nsrc\n'
+ )
+ expect(readDockerignore(testDir)).toEqual(['.env', 'src'])
+ })
+ })
})
diff --git a/packages/python-sdk/e2b/template/dockerignore.py b/packages/python-sdk/e2b/template/dockerignore.py
new file mode 100644
index 000000000..d6909a15d
--- /dev/null
+++ b/packages/python-sdk/e2b/template/dockerignore.py
@@ -0,0 +1,159 @@
+"""
+Matching of `.dockerignore` patterns, following the semantics Docker uses to
+filter the build context.
+
+Port of the pattern matcher from moby/patternmatcher (Apache-2.0):
+https://github.com/moby/patternmatcher
+"""
+
+import os
+import posixpath
+import re
+from typing import List
+
+from e2b.exceptions import TemplateException
+
+# Characters that have a meaning in a regex but not in a Docker pattern
+_LITERAL_REGEX_CHARS = set(".+()|{}$^")
+_WILDCARD_CHARS = re.compile(r"[*?\[\\]")
+_BACKSLASH_IS_SEPARATOR = os.sep == "\\"
+
+
+def _clean(pattern: str) -> str:
+ # Equivalent of Go's filepath.Clean followed by filepath.ToSlash
+ if _BACKSLASH_IS_SEPARATOR:
+ pattern = pattern.replace("\\", "/")
+ return posixpath.normpath(re.sub("/+", "/", pattern))
+
+
+def _compile(pattern: str) -> "re.Pattern[str]":
+ regex = "^"
+ i, n = 0, len(pattern)
+ while i < n:
+ ch = pattern[i]
+ i += 1
+ if ch == "*":
+ if i < n and pattern[i] == "*":
+ i += 1
+ # Treat "**/" as "**"
+ if i < n and pattern[i] == "/":
+ i += 1
+ regex += ".*" if i >= n else "(.*/)?"
+ else:
+ regex += "[^/]*"
+ elif ch == "?":
+ regex += "[^/]"
+ elif ch == "[":
+ # Copy a bracket expression as is, a leading "^" negates it
+ j = i
+ if j < n and pattern[j] == "^":
+ j += 1
+ while j < n and pattern[j] != "]":
+ if pattern[j] == "\\" and not _BACKSLASH_IS_SEPARATOR:
+ j += 1
+ j += 1
+ regex += pattern[i - 1 : j + 1]
+ i = j + 1
+ elif ch in _LITERAL_REGEX_CHARS:
+ regex += "\\" + ch
+ elif ch == "\\" and not _BACKSLASH_IS_SEPARATOR:
+ # Escape the next character
+ if i < n:
+ regex += re.escape(pattern[i])
+ i += 1
+ else:
+ regex += "\\\\"
+ else:
+ regex += ch
+ return re.compile(regex + "$")
+
+
+class _Pattern:
+ def __init__(self, cleaned_pattern: str, exclusion: bool):
+ self.exclusion = exclusion
+ self.dirs = cleaned_pattern.split("/")
+ self._regex = _compile(cleaned_pattern)
+
+ def match(self, path: str) -> bool:
+ return self._regex.match(path) is not None
+
+
+class PatternMatcher:
+ """
+ Match paths relative to the context root against `.dockerignore` patterns.
+
+ A pattern that matches a directory excludes everything under it, a leading
+ `/` is ignored, and `!` patterns re-include paths (the last matching
+ pattern wins).
+ """
+
+ def __init__(self, patterns: List[str]):
+ self._patterns: List[_Pattern] = []
+ for original in patterns:
+ pattern = original.strip()
+ if not pattern or pattern.startswith("#"):
+ continue
+ exclusion = pattern.startswith("!")
+ if exclusion:
+ pattern = pattern[1:].strip()
+ if not pattern:
+ continue
+ pattern = _clean(pattern)
+ if len(pattern) > 1 and pattern.startswith("/"):
+ pattern = pattern[1:]
+ try:
+ self._patterns.append(_Pattern(pattern, exclusion))
+ except re.error as e:
+ raise TemplateException(
+ f"Invalid ignore pattern '{original}': {e}"
+ ) from e
+
+ def matches(self, path: str) -> bool:
+ """
+ Whether the path or one of its parent directories is excluded.
+
+ :param path: Slash-separated path relative to the context root
+ :return: True if the path is excluded
+ """
+ parent_path = posixpath.dirname(path)
+ parent_dirs = parent_path.split("/") if parent_path else []
+
+ matched = False
+ for pattern in self._patterns:
+ # An inclusion can't change an already matched path, and an
+ # exclusion can't change a path that hasn't matched yet
+ if pattern.exclusion != matched:
+ continue
+ match = pattern.match(path) or any(
+ pattern.match("/".join(parent_dirs[: i + 1]))
+ for i in range(len(parent_dirs))
+ )
+ if match:
+ matched = not pattern.exclusion
+ return matched
+
+ def may_match_under(self, dir_path: str) -> bool:
+ """
+ Whether a `!` pattern could re-include a path under the directory,
+ in which case an excluded directory must still be walked.
+
+ :param dir_path: Slash-separated directory path relative to the context root
+ :return: True if a path under the directory could be re-included
+ """
+ dir_segments = dir_path.split("/")
+ for pattern in self._patterns:
+ if pattern.exclusion and self._may_match_under(pattern, dir_segments):
+ return True
+ return False
+
+ @staticmethod
+ def _may_match_under(pattern: _Pattern, dir_segments: List[str]) -> bool:
+ for i, dir_segment in enumerate(dir_segments):
+ if i >= len(pattern.dirs):
+ return False
+ segment = pattern.dirs[i]
+ if "**" in segment:
+ return True
+ if not _WILDCARD_CHARS.search(segment) and segment != dir_segment:
+ return False
+ return len(pattern.dirs) > len(dir_segments)
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index a81eb0e24..5cf259a43 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -766,7 +766,7 @@ class TemplateBase(ClientFactory):
Create a new template builder instance.
:param file_context_path: Base path for resolving relative file paths in copy operations
- :param file_ignore_patterns: List of glob patterns to ignore when copying files
+ :param file_ignore_patterns: Patterns in `.dockerignore` syntax for files to exclude when copying. They are applied after the `.dockerignore` file in the context directory, so they take precedence over it. An invalid pattern (such as an unterminated `[`) raises a :class:`TemplateException`. Brace expansion (`{a,b}`) is not supported, as in Docker
"""
self._default_base_image: str = "e2bdev/base"
self._base_image: Optional[str] = self._default_base_image
@@ -1249,8 +1249,8 @@ class TemplateBase(ClientFactory):
dest,
self._file_context_path,
[
- *self._file_ignore_patterns,
*read_dockerignore(self._file_context_path),
+ *self._file_ignore_patterns,
],
resolve_symlinks
if resolve_symlinks is not None
diff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.py
index b61101b30..9c9757818 100644
--- a/packages/python-sdk/e2b/template/utils.py
+++ b/packages/python-sdk/e2b/template/utils.py
@@ -1,5 +1,6 @@
import hashlib
import os
+import posixpath
import tarfile
import tempfile
import json
@@ -12,6 +13,7 @@ from typing import IO, List, Optional, Union
from e2b.exceptions import TemplateException
from e2b.template.consts import BASE_STEP_NAME, FINALIZE_STEP_NAME
+from e2b.template.dockerignore import PatternMatcher
def make_traceback(caller_frame: Optional[FrameType]) -> Optional[TracebackType]:
@@ -114,7 +116,7 @@ def read_dockerignore(context_path: str) -> List[str]:
if not os.path.exists(dockerignore_path):
return []
- with open(dockerignore_path, "r", encoding="utf-8") as f:
+ with open(dockerignore_path, "r", encoding="utf-8-sig") as f:
content = f.read()
return [
@@ -134,6 +136,35 @@ def normalize_path(path: str) -> str:
return path.replace(os.sep, "/")
+def _normalize_ignore_pattern(pattern: str, context_path: str) -> str:
+ """
+ Make an absolute ignore pattern that points into the context relative to it.
+ Other patterns are anchored at the context root, a leading `/` is ignored.
+
+ :param pattern: Ignore pattern
+ :param context_path: Absolute path of the context directory
+ :return: The normalized pattern
+ """
+ pattern = pattern.strip()
+ negated = pattern.startswith("!")
+ if negated:
+ pattern = pattern[1:].strip()
+ if os.path.isabs(pattern):
+ try:
+ relative = os.path.relpath(pattern, context_path)
+ except ValueError:
+ # Different drive on Windows
+ relative = None
+ if (
+ relative is not None
+ and relative != "."
+ and relative != ".."
+ and not relative.startswith(".." + os.sep)
+ ):
+ pattern = normalize_path(relative)
+ return ("!" if negated else "") + pattern
+
+
def get_all_files_in_path(
src: str,
context_path: str,
@@ -143,40 +174,83 @@ def get_all_files_in_path(
"""
Get all files for a given path and ignore patterns.
+ Ignore patterns follow `.dockerignore` semantics: they are relative to the
+ context root, a pattern matching a directory excludes everything under it,
+ and `!` patterns re-include paths (the last matching pattern wins).
+ The context root is never excluded.
+
:param src: Path to the source directory
:param context_path: Base directory for resolving relative paths
- :param ignore_patterns: Ignore patterns
+ :param ignore_patterns: Ignore patterns in `.dockerignore` syntax
:param include_directories: Whether to include directories
:return: Array of files
"""
files = set()
- # Use glob to find all files/directories matching the pattern under context_path
abs_context_path = os.path.abspath(context_path)
+ matcher = PatternMatcher(
+ [_normalize_ignore_pattern(p, abs_context_path) for p in ignore_patterns]
+ )
+
+ def walk(dir_path: str, dir_relative_path: str) -> None:
+ with os.scandir(dir_path) as entries:
+ for entry in entries:
+ relative_path = (
+ entry.name
+ if dir_relative_path == "."
+ else f"{dir_relative_path}/{entry.name}"
+ )
+ ignored = matcher.matches(relative_path)
+ if not ignored:
+ files.add(entry.path)
+ if entry.is_dir(follow_symlinks=False) and (
+ not ignored or matcher.may_match_under(relative_path)
+ ):
+ walk(entry.path, relative_path)
+
+ # Use glob to find all files/directories matching the pattern under context_path
files_glob = glob.glob(
src,
flags=glob.GLOBSTAR | glob.DOTMATCH,
root_dir=abs_context_path,
- exclude=ignore_patterns,
)
+ matches = []
for file in files_glob:
- # Join it with abs_context_path to get the absolute path
- file_path = os.path.join(abs_context_path, file)
-
- if os.path.isdir(file_path):
+ # Join it with abs_context_path to get the absolute path, dropping
+ # any "." and ".." segments from src
+ file_path = os.path.normpath(os.path.join(abs_context_path, file))
+ relative_path = normalize_path(os.path.relpath(file_path, abs_context_path))
+ matches.append((file_path, relative_path))
+
+ # Visit parents before their children, so paths under an already walked
+ # directory are not walked again
+ matches.sort(key=lambda m: 0 if m[1] == "." else m[1].count("/") + 1)
+ walked_dirs = set()
+
+ def is_under_walked_dir(relative_path: str) -> bool:
+ if "." in walked_dirs:
+ return True
+ parent = posixpath.dirname(relative_path)
+ while parent:
+ if parent in walked_dirs:
+ return True
+ parent = posixpath.dirname(parent)
+ return False
+
+ for file_path, relative_path in matches:
+ if is_under_walked_dir(relative_path):
+ continue
+ if relative_path != "." and matcher.matches(relative_path):
+ continue
+
+ # Symlinks are not followed, the link itself is copied
+ if os.path.isdir(file_path) and not os.path.islink(file_path):
# If it's a directory, add the directory and all entries recursively
if include_directories:
files.add(file_path)
- dir_files = glob.glob(
- normalize_path(file) + "/**/*",
- flags=glob.GLOBSTAR | glob.DOTMATCH,
- root_dir=abs_context_path,
- exclude=ignore_patterns,
- )
- for dir_file in dir_files:
- dir_file_path = os.path.join(abs_context_path, dir_file)
- files.add(dir_file_path)
+ walk(file_path, relative_path)
+ walked_dirs.add(relative_path)
else:
files.add(file_path)
@@ -200,7 +274,7 @@ def calculate_files_hash(
:param src: Source path pattern for files to copy
:param dest: Destination path where files will be copied
:param context_path: Base directory for resolving relative paths
- :param ignore_patterns: Glob patterns to ignore
+ :param ignore_patterns: Ignore patterns in `.dockerignore` syntax
:param resolve_symlinks: Whether to resolve symbolic links when hashing
:param stack_trace: Optional stack trace for error reporting
@@ -223,7 +297,9 @@ def calculate_files_hash(
# Only include stable metadata (mode, size)
# Exclude uid, gid, and mtime to ensure consistent hashes across environments
hash_obj.update(str(stat_info.st_mode).encode())
- hash_obj.update(str(stat_info.st_size).encode())
+ # A directory's size depends on the filesystem, not on the copied files
+ if not stat.S_ISDIR(stat_info.st_mode):
+ hash_obj.update(str(stat_info.st_size).encode())
for file in files:
# Hash the relative path
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index a5f144cc4..3672748a3 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -132,8 +132,8 @@ class AsyncTemplate(TemplateBase):
template._template._file_context_path,
file_info.url,
[
- *template._template._file_ignore_patterns,
*read_dockerignore(template._template._file_context_path),
+ *template._template._file_ignore_patterns,
],
resolve_symlinks,
gzip,
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index d6c8b46c5..f42bb5c3b 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -132,8 +132,8 @@ class Template(TemplateBase):
template._template._file_context_path,
file_info.url,
[
- *template._template._file_ignore_patterns,
*read_dockerignore(template._template._file_context_path),
+ *template._template._file_ignore_patterns,
],
resolve_symlinks,
gzip,
diff --git a/packages/python-sdk/tests/shared/template/utils/test_get_all_files_in_path.py b/packages/python-sdk/tests/shared/template/utils/test_get_all_files_in_path.py
index fc1faa8a5..88a9bf0d3 100644
--- a/packages/python-sdk/tests/shared/template/utils/test_get_all_files_in_path.py
+++ b/packages/python-sdk/tests/shared/template/utils/test_get_all_files_in_path.py
@@ -1,7 +1,13 @@
import os
+import sys
import tempfile
import pytest
-from e2b.template.utils import get_all_files_in_path
+from e2b.exceptions import TemplateException
+from e2b.template.utils import (
+ calculate_files_hash,
+ get_all_files_in_path,
+ read_dockerignore,
+)
class TestGetAllFilesInPath:
@@ -217,7 +223,9 @@ class TestGetAllFilesInPath:
files = get_all_files_in_path("src", test_dir, ["**/tests/**", "**/*.spec.*"])
- assert len(files) == 6 # 3 files + 3 directories (src, components, utils)
+ # 3 files + 4 directories (src, components, utils and the emptied tests,
+ # since `tests/**` matches the contents of `tests`, as in Docker)
+ assert len(files) == 7
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)
@@ -324,11 +332,190 @@ class TestGetAllFilesInPath:
files = get_all_files_in_path("src", test_dir, ["**/ui/**"])
- assert (
- len(files) == 7
- ) # 3 files + 4 directories (src, components, forms, utils)
+ # 3 files + 5 directories (src, components, forms, utils and the emptied
+ # ui, since `ui/**` matches the contents of `ui`, as in Docker)
+ assert len(files) == 8
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)
+
+
+class TestDockerignoreSemantics:
+ PATTERNS = [".env", "node_modules", ".git", "**/*.spec.*", "src/generated"]
+
+ @pytest.fixture
+ def test_dir(self):
+ """Create a build context with files that are usually ignored."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ for path, content in {
+ ".env": "SECRET=1",
+ "node_modules/pkg/index.js": "x",
+ "src/app.ts": "x",
+ "src/app.spec.ts": "x",
+ "src/generated/api.ts": "x",
+ "src/node_modules/lib.js": "x",
+ ".git/HEAD": "ref",
+ }.items():
+ full_path = os.path.join(tmpdir, path)
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
+ with open(full_path, "w") as f:
+ f.write(content)
+ yield tmpdir
+
+ @staticmethod
+ def relative_paths(src, test_dir, ignore_patterns):
+ return sorted(
+ os.path.relpath(f, test_dir).replace(os.sep, "/")
+ for f in get_all_files_in_path(src, test_dir, ignore_patterns)
+ )
+
+ @pytest.mark.parametrize("src", [".", "./", "./src", "src", "src/.", "src/../src"])
+ def test_should_exclude_ignored_directories_with_their_contents(
+ self, test_dir, src
+ ):
+ expected = ["src", "src/app.ts", "src/node_modules", "src/node_modules/lib.js"]
+ if src in (".", "./"):
+ expected = [".", *expected]
+ assert self.relative_paths(src, test_dir, self.PATTERNS) == expected
+
+ def test_should_ignore_a_leading_slash_and_a_trailing_slash(self, test_dir):
+ files = self.relative_paths(".", test_dir, ["/node_modules", "/.git/", "src/"])
+ assert files == [".", ".env"]
+
+ def test_should_never_exclude_the_context_root(self, test_dir):
+ files = self.relative_paths(".", test_dir, [".", ".*", "src", "node_modules"])
+ assert files == ["."]
+
+ def test_should_not_copy_paths_inside_an_ignored_directory(self, test_dir):
+ assert self.relative_paths("node_modules/pkg", test_dir, ["node_modules"]) == []
+
+ def test_should_reinclude_paths_matched_by_a_negated_pattern(self, test_dir):
+ files = self.relative_paths(
+ ".",
+ test_dir,
+ ["*", "!src", "src/generated", "!node_modules/pkg/index.js"],
+ )
+ assert files == [
+ ".",
+ "node_modules/pkg/index.js",
+ "src",
+ "src/app.spec.ts",
+ "src/app.ts",
+ "src/node_modules",
+ "src/node_modules/lib.js",
+ ]
+
+ def test_should_make_absolute_patterns_inside_the_context_relative(self, test_dir):
+ files = self.relative_paths(
+ ".",
+ test_dir,
+ [
+ os.path.join(test_dir, "src"),
+ os.path.join(test_dir, "node_modules", "**"),
+ ".git",
+ ],
+ )
+ assert files == [".", ".env", "node_modules"]
+
+ def test_should_match_regex_special_characters_literally(self, test_dir):
+ for name in ["file (1).txt", "c++", "a"]:
+ with open(os.path.join(test_dir, name), "w") as f:
+ f.write("x")
+ files = self.relative_paths("*", test_dir, ["file (1).txt", "c++", "a|b"])
+ assert "file (1).txt" not in files
+ assert "c++" not in files
+ assert "a" in files
+
+ def test_should_raise_on_an_invalid_pattern(self, test_dir):
+ with pytest.raises(TemplateException, match="Invalid ignore pattern '\\[abc'"):
+ get_all_files_in_path(".", test_dir, ["[abc"])
+
+ def test_should_keep_the_files_hash_stable_when_ignored_files_change(
+ self, test_dir
+ ):
+ def files_hash():
+ return calculate_files_hash(".", "/app", test_dir, [".git"], False, None)
+
+ before = files_hash()
+ with open(os.path.join(test_dir, ".git", "HEAD"), "a") as f:
+ f.write("x")
+ assert files_hash() == before
+
+ def test_should_strip_a_utf8_bom_from_dockerignore(self, test_dir):
+ with open(os.path.join(test_dir, ".dockerignore"), "w", encoding="utf-8") as f:
+ f.write("\ufeff.env\n# comment\n\nsrc\n")
+ assert read_dockerignore(test_dir) == [".env", "src"]
+
+ def test_should_match_a_caret_literally_outside_a_bracket_expression(
+ self, test_dir
+ ):
+ for name in ["report^draft.txt", "ax", "bx"]:
+ with open(os.path.join(test_dir, name), "w") as f:
+ f.write("x")
+ files = self.relative_paths("*", test_dir, ["report^draft.txt", "[^a]x"])
+ assert "report^draft.txt" not in files
+ assert "bx" not in files
+ assert "ax" in files
+
+ def test_should_not_walk_the_recursive_matches_of_a_directory_again(
+ self, test_dir, monkeypatch
+ ):
+ os.makedirs(os.path.join(test_dir, "a", "b", "c", "d", "e"))
+ scanned = []
+ scandir = os.scandir
+
+ def counting_scandir(path="."):
+ scanned.append(os.path.normpath(path))
+ return scandir(path)
+
+ monkeypatch.setattr(os, "scandir", counting_scandir)
+ files = self.relative_paths("**/*", test_dir, self.PATTERNS)
+ monkeypatch.undo()
+
+ assert files == [
+ "a",
+ "a/b",
+ "a/b/c",
+ "a/b/c/d",
+ "a/b/c/d/e",
+ "src",
+ "src/app.ts",
+ "src/node_modules",
+ "src/node_modules/lib.js",
+ ]
+ deepest = os.path.normpath(os.path.join(test_dir, "a", "b", "c", "d", "e"))
+ # Once by the walk, and at most once by the glob expansion
+ assert scanned.count(deepest) <= 2
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="Symlinks need privileges")
+ def test_should_copy_a_symlink_to_a_directory_without_its_contents(self, test_dir):
+ os.makedirs(os.path.join(test_dir, "real"))
+ with open(os.path.join(test_dir, "real", "secret.txt"), "w") as f:
+ f.write("x")
+ os.symlink("real", os.path.join(test_dir, "linked"))
+ assert self.relative_paths("linked", test_dir, []) == ["linked"]
+
+ def test_should_keep_the_files_hash_stable_when_ignored_files_grow_a_directory(
+ self, test_dir
+ ):
+ def files_hash():
+ return calculate_files_hash(
+ ".", "/app", test_dir, ["node_modules/*"], False, None
+ )
+
+ before = files_hash()
+ for i in range(300):
+ name = f"ignored-file-with-a-long-name-{i}"
+ with open(os.path.join(test_dir, "node_modules", name), "w") as f:
+ f.write("x")
+ assert files_hash() == before
+
+ def test_should_not_expand_braces(self, test_dir):
+ for name in ["a.txt", "b.{txt,md}"]:
+ with open(os.path.join(test_dir, name), "w") as f:
+ f.write("x")
+ files = self.relative_paths("*", test_dir, ["*.{txt,md}"])
+ assert "a.txt" in files
+ assert "b.{txt,md}" not in files