Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(template): replace third-party Dockerfile parsers with @e2b/dockerfile-utils / e2b-dockerfile-utils (BuildKit-style parser + .dockerignore matcher) (#1936)
devin-ai-integration[bot]cc85f69d5172
diff --git a/.changeset/dockerfile-utils-packages.md b/.changeset/dockerfile-utils-packages.mdnew file mode 100644index 000000000..6934c5c51--- /dev/null+++ b/.changeset/dockerfile-utils-packages.md@@ -0,0 +1,6 @@+---+'@e2b/dockerfile-utils': minor+'@e2b/dockerfile-utils-python': minor+---++Initial release: the Dockerfile parser and BuildKit-style shell lexer behind `Template.fromDockerfile` / `Template.from_dockerfile`, and the `.dockerignore` `PatternMatcher` used to filter the build context, published as standalone dependency-free packages (`@e2b/dockerfile-utils` on npm, `e2b-dockerfile-utils` on PyPI).diff --git a/.changeset/own-dockerfile-parser.md b/.changeset/own-dockerfile-parser.mdnew file mode 100644index 000000000..8ad9a15cc--- /dev/null+++ b/.changeset/own-dockerfile-parser.md@@ -0,0 +1,6 @@+---+'e2b': minor+'@e2b/python-sdk': minor+---++Replace the third-party Dockerfile parsers (`dockerfile-ast`, `dockerfile-parse`) used by `Template.fromDockerfile` / `Template.from_dockerfile` with a built-in parser ported from BuildKit. Quoted and escaped values in `ENV`/`ARG`/`COPY`, whitespace inside `RUN`/`CMD` arguments, mixed-case `AS` aliases, comments in line continuations, the `# escape=` directive, `COPY --chmod`, heredocs and `ENTRYPOINT` + `CMD` combination are now handled consistently in both SDKs. A `.dockerignore` line consisting of a lone `!` is now rejected, as Docker does, instead of being skipped.diff --git a/.github/scripts/build_release_itinerary.cjs b/.github/scripts/build_release_itinerary.cjsindex 5cad14ebc..ae6cb4e2f 100644--- a/.github/scripts/build_release_itinerary.cjs+++ b/.github/scripts/build_release_itinerary.cjs@@ -11,6 +11,8 @@ const labels = {e2b: 'JS SDK (e2b)','@e2b/python-sdk': 'Python SDK (e2b)','@e2b/cli': 'CLI (@e2b/cli)',+ '@e2b/dockerfile-utils': 'Dockerfile Utils JS (@e2b/dockerfile-utils)',+ '@e2b/dockerfile-utils-python': 'Dockerfile Utils Python (e2b-dockerfile-utils)',}const statusFile = process.argv[2]diff --git a/.github/workflows/dockerfile_utils_js_tests.yml b/.github/workflows/dockerfile_utils_js_tests.ymlnew file mode 100644index 000000000..0d4e386cd--- /dev/null+++ b/.github/workflows/dockerfile_utils_js_tests.yml@@ -0,0 +1,53 @@+name: Test Dockerfile Utils JS++on:+ workflow_call: {}++permissions:+ contents: read++jobs:+ test:+ defaults:+ run:+ working-directory: ./packages/dockerfile-utils-js+ shell: bash+ name: Dockerfile Utils JS - Build and test+ runs-on: ubuntu-22.04+ steps:+ - name: Checkout repository+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0++ - name: Parse .tool-versions+ uses: wistia/parse-tool-versions@32f568a4ffd4bfa7720ebf93f171597d1ebc979a # v2.1.1+ with:+ filename: '.tool-versions'+ uppercase: 'true'+ prefix: 'tool_version_'++ - name: Install pnpm+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0+ with:+ version: '${{ env.TOOL_VERSION_PNPM }}'++ - name: Setup Node+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0+ with:+ node-version: '${{ env.TOOL_VERSION_NODEJS }}'+ registry-url: 'https://registry.npmjs.org'+ cache: pnpm+ cache-dependency-path: pnpm-lock.yaml++ - name: Configure pnpm+ run: |+ pnpm config set auto-install-peers true+ pnpm config set exclude-links-from-lockfile true++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Test build+ run: pnpm build++ - name: Run tests+ run: pnpm testdiff --git a/.github/workflows/dockerfile_utils_python_tests.yml b/.github/workflows/dockerfile_utils_python_tests.ymlnew file mode 100644index 000000000..49d06a8c6--- /dev/null+++ b/.github/workflows/dockerfile_utils_python_tests.yml@@ -0,0 +1,42 @@+name: Test Dockerfile Utils Python++on:+ workflow_call: {}++permissions:+ contents: read++jobs:+ test:+ defaults:+ run:+ working-directory: ./packages/dockerfile-utils-python+ shell: bash+ name: Dockerfile Utils Python - Build and test+ runs-on: ubuntu-22.04+ steps:+ - name: Checkout repository+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0++ - name: Parse .tool-versions+ uses: wistia/parse-tool-versions@32f568a4ffd4bfa7720ebf93f171597d1ebc979a # v2.1.1+ with:+ filename: '.tool-versions'+ uppercase: 'true'+ prefix: 'tool_version_'++ - name: Install uv+ uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0+ with:+ version: '${{ env.TOOL_VERSION_UV }}'+ python-version: '${{ env.TOOL_VERSION_PYTHON }}'+ enable-cache: true++ - name: Install dependencies+ run: uv sync --locked++ - name: Test build+ run: uv build++ - name: Run tests+ run: uv run pytest --verbosediff --git a/.github/workflows/pkg_artifacts.yml b/.github/workflows/pkg_artifacts.ymlindex 7e6897472..cec5de45f 100644--- a/.github/workflows/pkg_artifacts.yml+++ b/.github/workflows/pkg_artifacts.yml@@ -103,6 +103,23 @@ jobs:name: e2b-desktop-jspath: packages/desktop-js/*.tgz+ # Before the SDK is packed: `@e2b/dockerfile-utils` has no published version+ # this SDK could use yet, so the SDK's `workspace:^` range must resolve to+ # the exact prerelease packed here and both tarballs are installed together.+ - name: Pack Dockerfile Utils JS+ if: ${{ !cancelled() }}+ working-directory: packages/dockerfile-utils-js+ run: |+ pnpm version prerelease --preid=${{ env.BRANCH_ID }} --no-git-tag-version+ pnpm pack++ - name: Upload Dockerfile Utils JS artifact+ if: ${{ !cancelled() }}+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2+ with:+ name: e2b-dockerfile-utils-js+ path: packages/dockerfile-utils-js/*.tgz+# Independent of the CLI steps above: a CLI failure should still leave# reviewers a usable SDK tarball, as it did before the CLI moved ahead of it.- name: Pack JS SDK@@ -126,11 +143,29 @@ jobs:python-version: '${{ env.TOOL_VERSION_PYTHON }}'enable-cache: true+ # Before the Python SDK is built: the SDK's `e2b-dockerfile-utils` range cannot+ # be satisfied by the unreleased package, so the SDK is pinned to the exact+ # preview version built here and both wheels are installed together.+ - name: Build Dockerfile Utils Python+ working-directory: packages/dockerfile-utils-python+ run: |+ BASE_VERSION=$(uv version --short)+ uv version "${BASE_VERSION}+${BRANCH_ID}"+ echo "DOCKERFILE_UTILS_PY_VERSION=$(uv version --short)" >> "$GITHUB_ENV"+ uv build++ - name: Upload Dockerfile Utils Python artifact+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2+ with:+ name: e2b-dockerfile-utils-python+ path: packages/dockerfile-utils-python/dist/*+- name: Build Python SDKworking-directory: packages/python-sdkrun: |BASE_VERSION=$(uv version --short)uv version "${BASE_VERSION}+${BRANCH_ID}"+ uv add --frozen "e2b-dockerfile-utils==${DOCKERFILE_UTILS_PY_VERSION}"uv build- name: Upload Python SDK artifact@@ -184,6 +219,8 @@ jobs:JS_VERSION=$(node -p "require('./packages/js-sdk/package.json').version")CLI_VERSION=$(node -p "require('./packages/cli/package.json').version")JS_TGZ=$(artifact_basename packages/js-sdk/*.tgz)+ DOCKERFILE_UTILS_JS_VERSION=$(node -p "require('./packages/dockerfile-utils-js/package.json').version")+ DOCKERFILE_UTILS_JS_TGZ=$(artifact_basename packages/dockerfile-utils-js/*.tgz)CLI_TGZ=$(artifact_basename packages/cli/*.tgz)CODE_INTERPRETER_JS_VERSION=$(node -p "require('./packages/code-interpreter-js/package.json').version")CODE_INTERPRETER_JS_TGZ=$(artifact_basename packages/code-interpreter-js/*.tgz)@@ -191,6 +228,7 @@ jobs:DESKTOP_JS_TGZ=$(artifact_basename packages/desktop-js/*.tgz)PY_VERSION=$(grep '^version' packages/python-sdk/pyproject.toml | head -1 | sed 's/.*"\(.*\)"/\1/')PY_WHL=$(artifact_basename packages/python-sdk/dist/*.whl)+ DOCKERFILE_UTILS_PY_WHL=$(artifact_basename packages/dockerfile-utils-python/dist/*.whl)CODE_INTERPRETER_PY_VERSION=$(grep '^version' packages/code-interpreter-python/pyproject.toml | head -1 | sed 's/.*"\(.*\)"/\1/')CODE_INTERPRETER_PY_WHL=$(artifact_basename packages/code-interpreter-python/dist/*.whl)DESKTOP_PY_VERSION=$(grep '^version' packages/desktop-python/pyproject.toml | head -1 | sed 's/.*"\(.*\)"/\1/')@@ -199,9 +237,9 @@ jobs:BODY="<!-- e2b-pkg-artifacts -->"$'\n'BODY+="### Package Artifacts"$'\n\n'BODY+="Built from ${GITHUB_SHA::7}. Download artifacts from [this workflow run](${RUN_URL})."$'\n\n'- BODY+="**JS SDK** (\`e2b@${JS_VERSION}\`):"$'\n'+ BODY+="**JS SDK** (\`e2b@${JS_VERSION}\`, with \`@e2b/dockerfile-utils@${DOCKERFILE_UTILS_JS_VERSION}\`):"$'\n'BODY+='```sh'$'\n'- BODY+="npm install ./${JS_TGZ}"$'\n'+ BODY+="npm install ./${DOCKERFILE_UTILS_JS_TGZ} ./${JS_TGZ}"$'\n'BODY+='```'$'\n\n'BODY+="**CLI** (\`@e2b/cli@${CLI_VERSION}\`):"$'\n'BODY+='```sh'$'\n'@@ -215,9 +253,9 @@ jobs:BODY+='```sh'$'\n'BODY+="npm install ./${DESKTOP_JS_TGZ}"$'\n'BODY+='```'$'\n\n'- BODY+="**Python SDK** (\`e2b==${PY_VERSION}\`):"$'\n'+ BODY+="**Python SDK** (\`e2b==${PY_VERSION}\`, with \`e2b-dockerfile-utils==${DOCKERFILE_UTILS_PY_VERSION}\`):"$'\n'BODY+='```sh'$'\n'- BODY+="pip install ./${PY_WHL}"$'\n'+ BODY+="pip install ./${DOCKERFILE_UTILS_PY_WHL} ./${PY_WHL}"$'\n'BODY+='```'$'\n\n'BODY+="**Code Interpreter Python SDK** (\`e2b-code-interpreter==${CODE_INTERPRETER_PY_VERSION}\`):"$'\n'BODY+='```sh'$'\n'diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex d9779f885..3fef4a5d3 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -22,6 +22,8 @@ jobs:code_interpreter_python: ${{ steps.code_interpreter_python.outputs.release }}desktop_js: ${{ steps.desktop_js.outputs.release }}desktop_python: ${{ steps.desktop_python.outputs.release }}+ dockerfile_utils_js: ${{ steps.dockerfile_utils_js.outputs.release }}+ dockerfile_utils_python: ${{ steps.dockerfile_utils_python.outputs.release }}itinerary: ${{ steps.itinerary.outputs.itinerary }}steps:- name: Check the ref@@ -122,6 +124,20 @@ jobs:IS_RELEASE=$(./.github/scripts/is_release_for_package.sh "@e2b/desktop-python")echo "release=$IS_RELEASE" >> "$GITHUB_OUTPUT"+ - name: Check Dockerfile Utils JavaScript Release+ id: dockerfile_utils_js+ if: steps.version.outputs.release == 'true'+ run: |+ IS_RELEASE=$(./.github/scripts/is_release_for_package.sh "@e2b/dockerfile-utils")+ echo "release=$IS_RELEASE" >> "$GITHUB_OUTPUT"++ - name: Check Dockerfile Utils Python Release+ id: dockerfile_utils_python+ if: steps.version.outputs.release == 'true'+ run: |+ IS_RELEASE=$(./.github/scripts/is_release_for_package.sh "@e2b/dockerfile-utils-python")+ echo "release=$IS_RELEASE" >> "$GITHUB_OUTPUT"+- name: Build release itineraryid: itineraryif: steps.version.outputs.release == 'true'@@ -187,6 +203,18 @@ jobs:uses: ./.github/workflows/desktop_python_tests.ymlsecrets: inherit+ dockerfile-utils-js-tests:+ name: Dockerfile Utils JS Tests+ needs: [preflight]+ if: needs.preflight.outputs.dockerfile_utils_js == 'true'+ uses: ./.github/workflows/dockerfile_utils_js_tests.yml++ dockerfile-utils-python-tests:+ name: Dockerfile Utils Python Tests+ needs: [preflight]+ if: needs.preflight.outputs.dockerfile_utils_python == 'true'+ uses: ./.github/workflows/dockerfile_utils_python_tests.yml+publish:name: Publishneeds:@@ -198,6 +226,8 @@ jobs:- code-interpreter-python-tests- desktop-js-tests- desktop-python-tests+ - dockerfile-utils-js-tests+ - dockerfile-utils-python-testsif: (!cancelled()) && !contains(needs.*.result, 'failure') && needs.preflight.outputs.release == 'true'uses: ./.github/workflows/publish_packages.ymlsecrets: inherit@@ -233,6 +263,8 @@ jobs:- code-interpreter-python-tests- desktop-js-tests- desktop-python-tests+ - dockerfile-utils-js-tests+ - dockerfile-utils-python-tests- publishif: failure()name: Release Failed - Slack Notificationdiff --git a/.github/workflows/sdk_tests.yml b/.github/workflows/sdk_tests.ymlindex 65e6d741a..4aeaea69a 100644--- a/.github/workflows/sdk_tests.yml+++ b/.github/workflows/sdk_tests.yml@@ -33,6 +33,8 @@ jobs:code_interpreter_python: ${{ steps.filter.outputs.code_interpreter_python }}desktop_js: ${{ steps.filter.outputs.desktop_js }}desktop_python: ${{ steps.filter.outputs.desktop_python }}+ dockerfile_utils_js: ${{ steps.filter.outputs.dockerfile_utils_js }}+ dockerfile_utils_python: ${{ steps.filter.outputs.dockerfile_utils_python }}steps:- name: Filter changed paths# On workflow_dispatch there is no PR diff and paths-filter would fall@@ -57,15 +59,18 @@ jobs:- 'tsconfig.sdk.json'- 'tsdown.sdk.config.mts'- 'packages/js-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-js/**/!(*.md)'python:- *shared- '.github/workflows/python_sdk_tests.yml'- 'packages/python-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-python/**/!(*.md)'cli:- *shared- '.github/workflows/cli_tests.yml'- 'packages/cli/**/!(*.md)'- 'packages/js-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-js/**/!(*.md)'code_interpreter_js:- *shared- '.github/workflows/code_interpreter_js_tests.yml'@@ -74,11 +79,13 @@ jobs:- 'vitest.sdk.config.mts'- 'packages/code-interpreter-js/**/!(*.md)'- 'packages/js-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-js/**/!(*.md)'code_interpreter_python:- *shared- '.github/workflows/code_interpreter_python_tests.yml'- 'packages/code-interpreter-python/**/!(*.md)'- 'packages/python-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-python/**/!(*.md)'desktop_js:- *shared- '.github/workflows/desktop_js_tests.yml'@@ -87,11 +94,23 @@ jobs:- 'vitest.sdk.config.mts'- 'packages/desktop-js/**/!(*.md)'- 'packages/js-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-js/**/!(*.md)'desktop_python:- *shared- '.github/workflows/desktop_python_tests.yml'- 'packages/desktop-python/**/!(*.md)'- 'packages/python-sdk/**/!(*.md)'+ - 'packages/dockerfile-utils-python/**/!(*.md)'+ dockerfile_utils_js:+ - *shared+ - '.github/workflows/dockerfile_utils_js_tests.yml'+ - 'tsconfig.sdk.json'+ - 'tsdown.sdk.config.mts'+ - 'packages/dockerfile-utils-js/**/!(*.md)'+ dockerfile_utils_python:+ - *shared+ - '.github/workflows/dockerfile_utils_python_tests.yml'+ - 'packages/dockerfile-utils-python/**/!(*.md)'js-tests:name: Production / JS SDK Tests@@ -229,6 +248,18 @@ jobs:secrets:E2B_API_KEY: ${{ secrets.E2B_API_KEY_STAGING }}+ dockerfile-utils-js-tests:+ name: Dockerfile Utils JS Tests+ needs: changes+ if: ${{ needs.changes.outputs.dockerfile_utils_js == 'true' || github.event_name == 'workflow_dispatch' }}+ uses: ./.github/workflows/dockerfile_utils_js_tests.yml++ dockerfile-utils-python-tests:+ name: Dockerfile Utils Python Tests+ needs: changes+ if: ${{ needs.changes.outputs.dockerfile_utils_python == 'true' || github.event_name == 'workflow_dispatch' }}+ uses: ./.github/workflows/dockerfile_utils_python_tests.yml+status:name: SDK Tests Status# `changes` is included so a failure in change-detection (which would skip the@@ -242,6 +273,8 @@ jobs:- code-interpreter-python-tests- desktop-js-tests- desktop-python-tests+ - dockerfile-utils-js-tests+ - dockerfile-utils-python-testsif: ${{ always() }}runs-on: ubuntu-lateststeps:diff --git a/packages/code-interpreter-python/uv.lock b/packages/code-interpreter-python/uv.lockindex 23dbc7910..adbd06106 100644--- a/packages/code-interpreter-python/uv.lock+++ b/packages/code-interpreter-python/uv.lock@@ -347,15 +347,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/23/94/71338e2f0146ac10747a5537b3a1e45256e66b7c229869eb0ee787111b41/datamodel_code_generator-0.64.0-py3-none-any.whl", hash = "sha256:b7cd8bd41a312aa997aec6150670bad781847c5b674f17e4d70e78208a0fb990", size = 374698, upload-time = "2026-06-14T17:24:48.809Z" },]-[[package]]-name = "dockerfile-parse"-version = "2.0.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/92/df/929ee0b5d2c8bd8d713c45e71b94ab57c7e11e322130724d54f469b2cd48/dockerfile-parse-2.0.1.tar.gz", hash = "sha256:3184ccdc513221983e503ac00e1aa504a2aa8f84e5de673c46b0b6eee99ec7bc", size = 24556, upload-time = "2023-07-18T13:36:07.897Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/7a/6c/79cd5bc1b880d8c1a9a5550aa8dacd57353fa3bb2457227e1fb47383eb49/dockerfile_parse-2.0.1-py2.py3-none-any.whl", hash = "sha256:bdffd126d2eb26acf1066acb54cb2e336682e1d72b974a40894fac76a4df17f6", size = 14845, upload-time = "2023-07-18T13:36:06.052Z" },-]-[[package]]name = "e2b"version = "2.53.1"@@ -363,7 +354,7 @@ source = { editable = "../python-sdk" }dependencies = [{ name = "attrs" },{ name = "connectrpc" },- { name = "dockerfile-parse" },+ { name = "e2b-dockerfile-utils" },{ name = "h2" },{ name = "httpx" },{ name = "packaging" },@@ -398,7 +389,7 @@ dev = [requires-dist = [{ name = "attrs", specifier = ">=23.2.0" },{ name = "connectrpc", specifier = ">=0.11.1,<0.12" },- { name = "dockerfile-parse", specifier = ">=2.0.1,<3" },+ { name = "e2b-dockerfile-utils", editable = "../dockerfile-utils-python" },{ name = "h2", specifier = ">=4.4.1,<5" },{ name = "httpx", specifier = ">=0.27.0,<1.0.0" },{ name = "packaging", specifier = ">=24.1" },@@ -471,6 +462,20 @@ dev = [{ name = "ty", specifier = ">=0.0.15,<0.0.16" },]+[[package]]+name = "e2b-dockerfile-utils"+version = "0.0.0"+source = { editable = "../dockerfile-utils-python" }++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=9.0.3,<10" },+ { name = "ruff", specifier = ">=0.11.12,<0.12" },+ { name = "ty", specifier = ">=0.0.15,<0.0.16" },+]+[[package]]name = "e2b-openapi-python-client"version = "0.26.2"diff --git a/packages/desktop-python/uv.lock b/packages/desktop-python/uv.lockindex 6f218baef..a1b8d4e9a 100644--- a/packages/desktop-python/uv.lock+++ b/packages/desktop-python/uv.lock@@ -341,15 +341,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/23/94/71338e2f0146ac10747a5537b3a1e45256e66b7c229869eb0ee787111b41/datamodel_code_generator-0.64.0-py3-none-any.whl", hash = "sha256:b7cd8bd41a312aa997aec6150670bad781847c5b674f17e4d70e78208a0fb990", size = 374698, upload-time = "2026-06-14T17:24:48.809Z" },]-[[package]]-name = "dockerfile-parse"-version = "2.0.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/92/df/929ee0b5d2c8bd8d713c45e71b94ab57c7e11e322130724d54f469b2cd48/dockerfile-parse-2.0.1.tar.gz", hash = "sha256:3184ccdc513221983e503ac00e1aa504a2aa8f84e5de673c46b0b6eee99ec7bc", size = 24556, upload-time = "2023-07-18T13:36:07.897Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/7a/6c/79cd5bc1b880d8c1a9a5550aa8dacd57353fa3bb2457227e1fb47383eb49/dockerfile_parse-2.0.1-py2.py3-none-any.whl", hash = "sha256:bdffd126d2eb26acf1066acb54cb2e336682e1d72b974a40894fac76a4df17f6", size = 14845, upload-time = "2023-07-18T13:36:06.052Z" },-]-[[package]]name = "e2b"version = "2.53.1"@@ -357,7 +348,7 @@ source = { editable = "../python-sdk" }dependencies = [{ name = "attrs" },{ name = "connectrpc" },- { name = "dockerfile-parse" },+ { name = "e2b-dockerfile-utils" },{ name = "h2" },{ name = "httpx" },{ name = "packaging" },@@ -392,7 +383,7 @@ dev = [requires-dist = [{ name = "attrs", specifier = ">=23.2.0" },{ name = "connectrpc", specifier = ">=0.11.1,<0.12" },- { name = "dockerfile-parse", specifier = ">=2.0.1,<3" },+ { name = "e2b-dockerfile-utils", editable = "../dockerfile-utils-python" },{ name = "h2", specifier = ">=4.4.1,<5" },{ name = "httpx", specifier = ">=0.27.0,<1.0.0" },{ name = "packaging", specifier = ">=24.1" },@@ -462,6 +453,20 @@ dev = [{ name = "ty", specifier = ">=0.0.15,<0.0.16" },]+[[package]]+name = "e2b-dockerfile-utils"+version = "0.0.0"+source = { editable = "../dockerfile-utils-python" }++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=9.0.3,<10" },+ { name = "ruff", specifier = ">=0.11.12,<0.12" },+ { name = "ty", specifier = ">=0.0.15,<0.0.16" },+]+[[package]]name = "e2b-openapi-python-client"version = "0.26.2"diff --git a/packages/dockerfile-utils-js/LICENSE b/packages/dockerfile-utils-js/LICENSEnew file mode 100644index 000000000..ec47fef19--- /dev/null+++ b/packages/dockerfile-utils-js/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2023 FoundryLabs, Inc.++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/dockerfile-utils-js/NOTICE b/packages/dockerfile-utils-js/NOTICEnew file mode 100644index 000000000..179a09761--- /dev/null+++ b/packages/dockerfile-utils-js/NOTICE@@ -0,0 +1,11 @@+E2B Dockerfile utils+Copyright 2025 FoundryLabs, Inc.++This product includes software derived from moby/buildkit+(https://github.com/moby/buildkit), licensed under the Apache License 2.0:+the Dockerfile parser and shell lexer are ported from frontend/dockerfile.++This product includes software derived from moby/patternmatcher+(https://github.com/moby/patternmatcher), licensed under the Apache License 2.0.+Copyright 2012-2017 Docker, Inc.+This product includes software developed at Docker, Inc. (https://www.docker.com).diff --git a/packages/dockerfile-utils-js/README.md b/packages/dockerfile-utils-js/README.mdnew file mode 100644index 000000000..7a7004be4--- /dev/null+++ b/packages/dockerfile-utils-js/README.md@@ -0,0 +1,35 @@+# @e2b/dockerfile-utils++Dockerfile parser and shell lexer ported from [BuildKit](https://github.com/moby/buildkit/tree/master/frontend/dockerfile) and a `.dockerignore` matcher ported from [moby/patternmatcher](https://github.com/moby/patternmatcher), with no runtime dependencies. Used by the [E2B SDK](https://www.npmjs.com/package/e2b) to implement `Template.fromDockerfile` and to filter the build context.++```ts+import { parseDockerfileAst, ShellLex } from '@e2b/dockerfile-utils'++const ast = parseDockerfileAst(`+FROM node:24 AS build+ENV KEY="a b" OTHER=c+RUN <<EOF+npm ci+npm run build+EOF+`)++for (const instruction of ast.instructions) {+ console.log(instruction.name, instruction.flags, instruction.args)+}++const lex = new ShellLex(ast.escapeToken)+lex.processWords('KEY="a b" OTHER=c') // ['KEY=a b', 'OTHER=c']+```++`parseDockerfileAst` handles parser directives (`# escape=`, `# syntax=`), comments (including inside line continuations), builder flags, JSON/exec forms and heredocs, and reports line numbers and warnings. `ShellLex` splits and unquotes words the way BuildKit does, preserving `$VAR` / `${VAR:-default}` references for later expansion.++```ts+import { PatternMatcher } from '@e2b/dockerfile-utils'++const matcher = new PatternMatcher(['node_modules', '*.log', '!keep.log'])+matcher.matches('node_modules/pkg/index.js') // true+matcher.matches('keep.log') // false+```++`PatternMatcher` applies `.dockerignore` semantics to slash-separated paths relative to the context root: a pattern matching a directory excludes everything under it, and `!` patterns re-include paths (the last matching pattern wins). An invalid pattern throws a plain `Error`.diff --git a/packages/dockerfile-utils-js/package.json b/packages/dockerfile-utils-js/package.jsonnew file mode 100644index 000000000..f217936fb--- /dev/null+++ b/packages/dockerfile-utils-js/package.json@@ -0,0 +1,62 @@+{+ "name": "@e2b/dockerfile-utils",+ "version": "0.0.0",+ "packageManager": "[email protected]",+ "description": "E2B Dockerfile utils - Dockerfile parser, shell lexer and .dockerignore matcher ported from BuildKit and Moby",+ "homepage": "https://e2b.dev/?utm_source=npm&utm_medium=referral&utm_campaign=package_homepage&utm_content=e2b-dockerfile-utils",+ "license": "Apache-2.0",+ "author": {+ "name": "FoundryLabs, Inc.",+ "email": "[email protected]",+ "url": "https://e2b.dev"+ },+ "bugs": "https://github.com/e2b-dev/e2b/issues",+ "repository": {+ "type": "git",+ "url": "https://github.com/e2b-dev/e2b",+ "directory": "packages/dockerfile-utils-js"+ },+ "publishConfig": {+ "access": "public"+ },+ "sideEffects": false,+ "main": "dist/index.js",+ "module": "dist/index.mjs",+ "types": "dist/index.d.ts",+ "scripts": {+ "prepublishOnly": "pnpm build",+ "build": "tsc --noEmit && tsdown",+ "dev": "tsdown --watch",+ "test": "vitest run",+ "typecheck": "tsc --noEmit",+ "lint": "oxlint --config ../../.oxlintrc.json src tests",+ "format": "prettier --write src/ tests/"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "@typescript/native": "catalog:",+ "tsdown": "catalog:",+ "typescript": "catalog:",+ "vitest": "catalog:"+ },+ "files": [+ "dist",+ "README.md",+ "LICENSE",+ "NOTICE",+ "package.json"+ ],+ "keywords": [+ "e2b",+ "dockerfile",+ "docker",+ "parser",+ "buildkit"+ ],+ "engines": {+ "node": ">=20.18.1 <21 || >=22"+ },+ "browserslist": [+ "defaults"+ ]+}diff --git a/packages/js-sdk/src/template/dockerignore.ts b/packages/dockerfile-utils-js/src/dockerignore.tssimilarity index 68%rename from packages/js-sdk/src/template/dockerignore.tsrename to packages/dockerfile-utils-js/src/dockerignore.tsindex 7ddb3da96..6d5ae226d 100644--- a/packages/js-sdk/src/template/dockerignore.ts+++ b/packages/dockerfile-utils-js/src/dockerignore.ts@@ -5,8 +5,6 @@* 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 patternconst LITERAL_REGEX_CHARS = new Set([@@ -21,8 +19,6 @@ 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, '\\$&')@@ -85,16 +81,80 @@ function translateClass(body: string, backslashIsEscape: boolean): string {return cls}-// Equivalent of Go's filepath.Clean followed by filepath.ToSlash-function clean(pattern: string): string {- if (backslashIsSeparator()) {- pattern = pattern.replace(/\\/g, '/')+// Equivalent of Go's filepath.Clean on a slash-separated path+function cleanPath(p: string): string {+ const rooted = p.startsWith('/')+ const out: string[] = []+ for (const segment of p.split('/')) {+ if (segment === '' || segment === '.') {+ continue+ }+ if (segment === '..') {+ if (out.length > 0 && out[out.length - 1] !== '..') {+ out.pop()+ } else if (!rooted) {+ out.push('..')+ }+ continue+ }+ out.push(segment)}- return path.posix.normalize(pattern).replace(/(.)\/$/, '$1')+ const cleaned = (rooted ? '/' : '') + out.join('/')+ return cleaned === '' ? '.' : cleaned}type Matcher = (p: string) => boolean+const BAD_PATTERN = 'syntax error in pattern'++// Advances over one (possibly escaped) character of a bracket expression+function classChar(pattern: string, i: number, backslashIsEscape: boolean) {+ const n = pattern.length+ if (i >= n || pattern[i] === '-' || pattern[i] === ']') {+ throw new Error(BAD_PATTERN)+ }+ if (pattern[i] === '\\' && backslashIsEscape) {+ i+++ if (i >= n) {+ throw new Error(BAD_PATTERN)+ }+ }+ i += (pattern.codePointAt(i) as number) > 0xffff ? 2 : 1+ if (i >= n) {+ throw new Error(BAD_PATTERN)+ }+ return i+}++// Rejects what Go's filepath.Match rejects (Docker validates patterns with+// it), as regex engines are more lenient about bracket expressions+function validatePattern(pattern: string, backslashIsEscape: boolean): void {+ const n = pattern.length+ let i = 0+ while (i < n) {+ const ch = pattern[i++]+ if (ch === '\\' && backslashIsEscape) {+ if (i >= n) {+ throw new Error(BAD_PATTERN)+ }+ i+++ } else if (ch === '[') {+ if (pattern[i] === '^') {+ i+++ }+ let ranges = 0+ while (!(ranges > 0 && pattern[i] === ']')) {+ i = classChar(pattern, i, backslashIsEscape)+ if (pattern[i] === '-') {+ i = classChar(pattern, i + 1, backslashIsEscape)+ }+ ranges+++ }+ i+++ }+ }+}+enum MatchType {Exact = 'exact',Prefix = 'prefix',@@ -104,11 +164,11 @@ enum MatchType {// Like moby, use plain string checks for patterns without wildcards and only// fall back to a regex otherwise-function compile(pattern: string): Matcher {+function compile(pattern: string, backslashIsEscape: boolean): Matcher {+ validatePattern(pattern, backslashIsEscape)let regex = '^'let matchType = MatchType.Exactconst n = pattern.length- const backslashIsEscape = !backslashIsSeparator()let i = 0while (i < n) {const first = i === 0@@ -200,45 +260,79 @@ interface Pattern {match: Matcher}+export interface PatternMatcherOptions {+ /**+ * Whether `\` separates path segments (as on Windows) instead of escaping+ * the next character in a pattern.+ *+ * @default false+ */+ backslashIsSeparator?: boolean+}+/*** 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).+ *+ * @throws {Error} If a pattern is invalid, such as an unterminated `[`*/export class PatternMatcher {- private readonly patterns: Pattern[] = []+ private readonly compiled: Pattern[] = []+ private readonly backslashIsSeparator: boolean- constructor(patterns: string[]) {+ /**+ * The cleaned patterns, `!` prefixed for exclusions. Empty lines and+ * comments are dropped.+ */+ readonly patterns: string[] = []++ constructor(patterns: string[], options: PatternMatcherOptions = {}) {+ const backslashIsSeparator = options.backslashIsSeparator ?? false+ this.backslashIsSeparator = backslashIsSeparatorfor (const original of patterns) {+ if (original.startsWith('#')) {+ continue+ }let pattern = original.trim()- if (!pattern || pattern.startsWith('#')) {+ if (!pattern) {continue}const exclusion = pattern.startsWith('!')if (exclusion) {pattern = pattern.slice(1).trim()if (!pattern) {- continue+ throw new Error(+ `Invalid ignore pattern '${original}': illegal exclusion pattern`+ )}}- pattern = clean(pattern)+ if (backslashIsSeparator) {+ pattern = pattern.replace(/\\/g, '/')+ }+ pattern = cleanPath(pattern)if (pattern.length > 1 && pattern.startsWith('/')) {pattern = pattern.slice(1)}let match: Matchertry {- match = compile(pattern)+ match = compile(pattern, !backslashIsSeparator)} catch (err) {- throw new TemplateError(+ throw new Error(`Invalid ignore pattern '${original}': ${(err as Error).message}`)}- this.patterns.push({ exclusion, dirs: pattern.split('/'), match })+ this.compiled.push({ exclusion, dirs: pattern.split('/'), match })+ this.patterns.push((exclusion ? '!' : '') + pattern)}}+ private toSlash(p: string): string {+ return this.backslashIsSeparator ? p.replace(/\\/g, '/') : p+ }+/*** Whether the path is excluded. Like BuildKit, the patterns are evaluated* on each parent directory first, and a pattern that matched a parent@@ -248,13 +342,13 @@ export class PatternMatcher {* @returns True if the path is excluded*/matches(p: string): boolean {- const segments = p.split('/')+ const segments = this.toSlash(p).split('/')let parentMatched: boolean[] = []let matched = falsefor (let depth = 1; depth <= segments.length; depth++) {const current = segments.slice(0, depth).join('/')matched = false- parentMatched = this.patterns.map((pattern, i) => {+ parentMatched = this.compiled.map((pattern, i) => {let match = parentMatched[i] ?? falseif (!match) {// An inclusion can't change an already matched path, and an@@ -281,8 +375,8 @@ export class PatternMatcher {* @returns True if a path under the directory could be re-included*/mayMatchUnder(dirPath: string): boolean {- const dirSegments = dirPath.split('/')- return this.patterns.some(+ const dirSegments = this.toSlash(dirPath).split('/')+ return this.compiled.some((pattern) =>pattern.exclusion && patternMayMatchUnder(pattern, dirSegments))diff --git a/packages/dockerfile-utils-js/src/index.ts b/packages/dockerfile-utils-js/src/index.tsnew file mode 100644index 000000000..64d6e65e4--- /dev/null+++ b/packages/dockerfile-utils-js/src/index.ts@@ -0,0 +1,17 @@+export { ShellLex, isSpace } from './lexer'+export type { ShellLexOptions } from './lexer'+export {+ DockerfileSyntaxError,+ chompHeredocContent,+ parseDockerfileAst,+ parseHeredoc,+ parseWords,+} from './syntax'+export type {+ DockerfileAst,+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileWarning,+} from './syntax'+export { PatternMatcher } from './dockerignore'+export type { PatternMatcherOptions } from './dockerignore'diff --git a/packages/dockerfile-utils-js/src/lexer.ts b/packages/dockerfile-utils-js/src/lexer.tsnew file mode 100644index 000000000..02af6e7c9--- /dev/null+++ b/packages/dockerfile-utils-js/src/lexer.ts@@ -0,0 +1,577 @@+/**+ * Shell-style word lexer for Dockerfile instruction arguments.+ *+ * This is a port of BuildKit's `frontend/dockerfile/shell` lexer+ * (https://github.com/moby/buildkit). Variable references (`$VAR`,+ * `${VAR:-default}`, ...) are expanded from the `env` option; without it+ * they are kept verbatim, so they can be evaluated later inside the sandbox.+ */++const EOF = null++/** Equivalent of Go's `unicode.IsSpace`. */+export function isSpace(ch: string): boolean {+ return /^[\t\n\v\f\r \u0085\u00a0\p{Z}]$/u.test(ch)+}++function isLetter(ch: string): boolean {+ return /^\p{L}$/u.test(ch)+}++function isDigit(ch: string): boolean {+ return /^\p{Nd}$/u.test(ch)+}++function isSpecialParam(ch: string): boolean {+ return '@*#?-$!0'.includes(ch)+}++class Scanner {+ private readonly chars: string[]+ private pos = 0++ constructor(input: string) {+ this.chars = Array.from(input)+ }++ peek(): string | null {+ return this.pos < this.chars.length ? this.chars[this.pos] : EOF+ }++ next(): string | null {+ return this.pos < this.chars.length ? this.chars[this.pos++] : EOF+ }+}++class Words {+ private words: string[] = []+ private buf = ''+ private inWord = false++ addChar(ch: string) {+ if (isSpace(ch) && this.inWord) {+ if (this.buf.length !== 0) {+ this.words.push(this.buf)+ this.buf = ''+ this.inWord = false+ }+ } else if (!isSpace(ch)) {+ this.addRawChar(ch)+ }+ }++ addRawChar(ch: string) {+ this.buf += ch+ this.inWord = true+ }++ addString(str: string) {+ for (const ch of str) {+ this.addChar(ch)+ }+ }++ addRawString(str: string) {+ this.buf += str+ this.inWord = true+ }++ getWords(): string[] {+ if (this.buf.length > 0) {+ this.words.push(this.buf)+ this.buf = ''+ this.inWord = false+ }+ return this.words+ }+}++export interface ShellLexOptions {+ /** Keep quote characters in the output instead of removing them. */+ rawQuotes?: boolean+ /** Keep escape characters in the output instead of removing them. */+ rawEscapes?: boolean+ /** Do not treat quote characters specially at all. */+ skipProcessQuotes?: boolean+ /** Variables to expand. Defaults to no variables. */+ env?: ReadonlyMap<string, string>+ /**+ * Keep references to variables missing from `env` verbatim instead of+ * expanding them to an empty string. Defaults to `true`.+ */+ skipUnsetEnv?: boolean+}++export class ShellLex {+ private readonly escapeToken: string+ private readonly rawQuotes: boolean+ private readonly rawEscapes: boolean+ private readonly skipProcessQuotes: boolean+ private readonly env: ReadonlyMap<string, string>+ private readonly skipUnsetEnv: boolean++ constructor(escapeToken: string, options: ShellLexOptions = {}) {+ this.escapeToken = escapeToken+ this.rawQuotes = options.rawQuotes ?? false+ this.rawEscapes = options.rawEscapes ?? false+ this.skipProcessQuotes = options.skipProcessQuotes ?? false+ this.env = options.env ?? new Map()+ this.skipUnsetEnv = options.skipUnsetEnv ?? true+ }++ /** Process a single word: remove quotes/escapes, keep whitespace. */+ processWord(word: string): string {+ return this.process(word).result+ }++ /** Process a line into whitespace separated words, honoring quotes. */+ processWords(word: string): string[] {+ return this.process(word).words+ }++ private process(word: string): { result: string; words: string[] } {+ const sw = new ShellWord(+ new Scanner(word),+ this.escapeToken,+ this.rawQuotes,+ this.rawEscapes,+ this.skipProcessQuotes,+ this.env,+ this.skipUnsetEnv+ )+ try {+ return sw.processStopOn(EOF, this.rawEscapes)+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ throw new Error(`failed to process ${JSON.stringify(word)}: ${message}`)+ }+ }+}++class ShellWord {+ constructor(+ private readonly scanner: Scanner,+ private readonly escapeToken: string,+ private readonly rawQuotes: boolean,+ private rawEscapes: boolean,+ private readonly skipProcessQuotes: boolean,+ private readonly env: ReadonlyMap<string, string>,+ private readonly skipUnsetEnv: boolean+ ) {}++ processStopOn(+ stopChar: string | null,+ rawEscapes: boolean+ ): { result: string; words: string[] } {+ let result = ''+ const words = new Words()++ const previousRawEscapes = this.rawEscapes+ this.rawEscapes = rawEscapes+ try {+ while (this.scanner.peek() !== EOF) {+ let ch = this.scanner.peek() as string++ if (stopChar !== EOF && ch === stopChar) {+ this.scanner.next()+ return { result, words: words.getWords() }+ }++ const fn = this.specialHandler(ch)+ if (fn) {+ const tmp = fn()+ result += tmp+ if (ch === '$') {+ words.addString(tmp)+ } else {+ words.addRawString(tmp)+ }+ continue+ }++ ch = this.scanner.next() as string+ if (ch === this.escapeToken) {+ if (this.rawEscapes) {+ words.addRawChar(ch)+ result += ch+ }++ // the escape token escapes the next character, except at end of line+ const next = this.scanner.next()+ if (next === EOF) {+ break+ }+ ch = next+ words.addRawChar(ch)+ } else {+ words.addChar(ch)+ }+ result += ch+ }+ } finally {+ this.rawEscapes = previousRawEscapes+ }++ if (stopChar !== EOF) {+ throw new Error(+ `unexpected end of statement while looking for matching ${stopChar}`+ )+ }+ return { result, words: words.getWords() }+ }++ private specialHandler(ch: string): (() => string) | undefined {+ switch (ch) {+ case '$':+ return () => this.processDollar()+ case '<':+ return () => this.processPossibleHeredoc()+ case "'":+ return this.skipProcessQuotes+ ? undefined+ : () => this.processSingleQuote()+ case '"':+ return this.skipProcessQuotes+ ? undefined+ : () => this.processDoubleQuote()+ default:+ return undefined+ }+ }++ private processSingleQuote(): string {+ // All chars between single quotes are taken as-is; a single quote+ // cannot be escaped inside single quotes.+ let result = ''+ let ch = this.scanner.next() as string+ if (this.rawQuotes) {+ result += ch+ }++ for (;;) {+ const next = this.scanner.next()+ if (next === EOF) {+ throw new Error(+ 'unexpected end of statement while looking for matching single-quote'+ )+ }+ ch = next+ if (ch === "'") {+ if (this.rawQuotes) {+ result += ch+ }+ return result+ }+ result += ch+ }+ }++ private processDoubleQuote(): string {+ // All chars up to the next " are taken as-is, even ', except `$`.+ // The escape token only escapes `"`, `$` and itself.+ let result = ''+ const open = this.scanner.next() as string+ if (this.rawQuotes) {+ result += open+ }++ for (;;) {+ const peeked = this.scanner.peek()+ if (peeked === EOF) {+ throw new Error(+ 'unexpected end of statement while looking for matching double-quote'+ )+ }+ if (peeked === '"') {+ const ch = this.scanner.next() as string+ if (this.rawQuotes) {+ result += ch+ }+ return result+ }+ if (peeked === '$') {+ result += this.processDollar()+ continue+ }++ let ch = this.scanner.next() as string+ if (ch === this.escapeToken) {+ if (this.rawEscapes) {+ result += ch+ }+ const after = this.scanner.peek()+ if (after === EOF) {+ // ignore escape token at end of word+ continue+ }+ if (after === '"' || after === '$' || after === this.escapeToken) {+ ch = this.scanner.next() as string+ }+ }+ result += ch+ }+ }++ private processDollar(): string {+ this.scanner.next() // '$'++ if (this.scanner.peek() !== '{') {+ const name = this.processName()+ if (name === '') {+ return '$'+ }+ const value = this.env.get(name)+ if (value === undefined && this.skipUnsetEnv) {+ return '$' + name+ }+ return value ?? ''+ }++ this.scanner.next() // '{'+ const first = this.scanner.peek()+ if (first === EOF) {+ throw new Error("syntax error: missing '}'")+ }+ if (first === '{' || first === '}' || first === ':') {+ throw new Error('syntax error: bad substitution')+ }++ const name = this.processName()+ let ch = this.scanner.next()+ if (ch === EOF) {+ throw new Error("syntax error: missing '}'")+ }+ let chs = ch+ const value = this.env.get(name)++ if (ch === '}') {+ if (value === undefined && this.skipUnsetEnv) {+ return '${' + name + '}'+ }+ return value ?? ''+ }++ let nullIsUnset = false+ if (ch === ':') {+ nullIsUnset = true+ const modifier = this.scanner.next()+ if (modifier === EOF) {+ throw new Error("syntax error: missing '}'")+ }+ ch = modifier+ chs += ch+ }++ if (!nullIsUnset) {+ if (ch === '/') {+ return this.processDollarReplace(name)+ }+ if (!'+-?#%'.includes(ch)) {+ throw new Error(`unsupported modifier (${chs}) in substitution`)+ }+ }++ const rawEscapes = ch === '#' || ch === '%'+ if (nullIsUnset && rawEscapes) {+ throw new Error(`unsupported modifier (${chs}) in substitution`)+ }+ const word = this.processStopOnOrMissingBrace('}', rawEscapes)+ if (value === undefined && this.skipUnsetEnv) {+ return '${' + name + chs + word + '}'+ }++ const unset = value === undefined || (nullIsUnset && value === '')+ switch (ch) {+ case '-':+ return unset ? word : (value as string)+ case '+':+ return unset ? '' : word+ case '?':+ if (value === undefined) {+ throw new Error(`${name}: ${word || 'is not allowed to be unset'}`)+ }+ if (unset) {+ throw new Error(`${name}: ${word || 'is not allowed to be empty'}`)+ }+ return value+ case '#':+ case '%': {+ // `#`/`%` remove the shortest match, `##`/`%%` the longest+ const greedy = word.startsWith(ch)+ const pattern = greedy ? word.slice(1) : word+ return ch === '%'+ ? trimSuffix(pattern, value ?? '', greedy)+ : trimPrefix(pattern, value ?? '', greedy)+ }+ default:+ throw new Error(`unsupported modifier (${chs}) in substitution`)+ }+ }++ private processDollarReplace(name: string): string {+ let op = '/'+ if (this.scanner.peek() === '/') {+ this.scanner.next()+ op = '//'+ }+ let pattern: string+ try {+ pattern = this.processStopOn('/', true).result+ } catch (err) {+ if (this.scanner.peek() === EOF) {+ throw new Error("syntax error: missing '/' in ${}")+ }+ throw err+ }+ const replacement = this.processStopOnOrMissingBrace('}', true)++ const value = this.env.get(name)+ if (value === undefined && this.skipUnsetEnv) {+ return '${' + name + op + pattern + '/' + replacement + '}'+ }+ const re = shellPatternToRegex(pattern, true, false, op === '//')+ return (value ?? '').replace(re, () => replacement)+ }++ private processStopOnOrMissingBrace(+ stopChar: string,+ rawEscapes: boolean+ ): string {+ try {+ return this.processStopOn(stopChar, rawEscapes).result+ } catch (err) {+ if (this.scanner.peek() === EOF) {+ throw new Error("syntax error: missing '}'")+ }+ throw err+ }+ }++ private processName(): string {+ // Read in a name (alphanumeric or _). A leading digit sequence or a+ // special parameter character is a complete name on its own.+ let name = ''+ for (;;) {+ const ch = this.scanner.peek()+ if (ch === EOF) {+ break+ }+ if (name.length === 0 && isDigit(ch)) {+ let digits = ''+ for (;;) {+ const d = this.scanner.peek()+ if (d === EOF || !isDigit(d)) {+ break+ }+ digits += this.scanner.next() as string+ }+ return digits+ }+ if (name.length === 0 && isSpecialParam(ch)) {+ return this.scanner.next() as string+ }+ if (!isLetter(ch) && !isDigit(ch) && ch !== '_') {+ break+ }+ name += this.scanner.next() as string+ }+ return name+ }++ private processPossibleHeredoc(): string {+ this.scanner.next() // '<'+ if (this.scanner.peek() !== '<') {+ return '<'+ }+ this.scanner.next()++ // a heredoc may have whitespace between `<<` and the terminator word+ let space = ''+ for (;;) {+ const ch = this.scanner.peek()+ if (ch !== '\t' && ch !== '\r' && ch !== ' ') {+ break+ }+ space += this.scanner.next() as string+ }+ return '<<' + space+ }+}++/**+ * Convert a shell wildcard pattern (`?` one character, `*` the shortest or,+ * when greedy, the longest run) to a regular expression. Bracket+ * expressions are not supported, like in BuildKit.+ */+function shellPatternToRegex(+ pattern: string,+ greedy: boolean,+ anchored: boolean,+ global = false+): RegExp {+ const chars = Array.from(pattern)+ let out = anchored ? '^' : ''+ const star = greedy ? '.*' : '.*?'+ for (let i = 0; i < chars.length; i++) {+ let ch = chars[i]+ if (ch === '*') {+ out += star+ continue+ }+ if (ch === '?') {+ out += '.'+ continue+ }+ if (ch === '\\') {+ // `}` and `/` are escaped to be part of the `${}` word, the escape+ // itself is not part of the pattern+ const next = chars[i + 1]+ if (next === '}' || next === '/') {+ continue+ }+ i+++ if (next !== '*' && next !== '?' && next !== '\\') {+ throw new Error(+ `invalid pattern (${pattern}) in substitution: invalid escape '\\${next ?? ''}'`+ )+ }+ ch = next+ }+ if ('[]{}.+()|^$*?\\'.includes(ch)) {+ out += '\\'+ }+ out += ch+ }+ return new RegExp(out, global ? 'gu' : 'u')+}++function trimPrefix(pattern: string, value: string, greedy: boolean): string {+ return value.replace(shellPatternToRegex(pattern, greedy, true), '')+}++/** Reverse a pattern without turning `a\*c` into `c*\a`. */+function reversePattern(pattern: string): string {+ const chars = Array.from(pattern)+ const out: string[] = []+ for (let i = 0; i < chars.length; i++) {+ if (chars[i] === '\\' && i + 1 < chars.length) {+ out.unshift(chars[i], chars[i + 1])+ i+++ } else {+ out.unshift(chars[i])+ }+ }+ return out.join('')+}++function reverseString(str: string): string {+ return Array.from(str).reverse().join('')+}++function trimSuffix(pattern: string, value: string, greedy: boolean): string {+ // regular expressions cannot find the shortest rightmost match, so both+ // the pattern and the value are reversed to turn it into a leftmost search+ return reverseString(+ trimPrefix(reversePattern(pattern), reverseString(value), greedy)+ )+}diff --git a/packages/dockerfile-utils-js/src/syntax.ts b/packages/dockerfile-utils-js/src/syntax.tsnew file mode 100644index 000000000..15c5a40d7--- /dev/null+++ b/packages/dockerfile-utils-js/src/syntax.ts@@ -0,0 +1,706 @@+/**+ * Dockerfile syntax parser.+ *+ * Port of BuildKit's `frontend/dockerfile/parser` (https://github.com/moby/buildkit):+ * handles parser directives (`# escape=`), comments, line continuations,+ * builder flags (`--chown=...`), JSON/exec forms and heredocs.+ */++import { ShellLex, isSpace } from './lexer'++export interface DockerfileHeredoc {+ name: string+ /** Raw content including trailing newlines of every line. */+ content: string+ /** `<<-`: leading tabs are stripped from content lines. */+ chomp: boolean+ /** Unquoted terminator: content is subject to variable expansion. */+ expand: boolean+ fileDescriptor: number+}++export interface DockerfileInstruction {+ /** Upper-cased instruction keyword, e.g. `RUN`. */+ name: string+ /** The full (continuation-joined) instruction line. */+ original: string+ /** Builder flags, e.g. `--chown=user:group`, with quotes removed. */+ flags: string[]+ /**+ * Instruction arguments. For `ENV` and `LABEL` these are+ * `[key, value, delimiter, ...]` triples where delimiter is `=` or ``.+ */+ args: string[]+ /** Arguments were given in JSON (exec) form. */+ json: boolean+ heredocs: DockerfileHeredoc[]+ startLine: number+ endLine: number+}++export interface DockerfileWarning {+ message: string+ line: number+}++export interface DockerfileAst {+ instructions: DockerfileInstruction[]+ escapeToken: string+ warnings: DockerfileWarning[]+}++export class DockerfileSyntaxError extends Error {+ constructor(+ message: string,+ public readonly line?: number+ ) {+ super(+ line === undefined+ ? `Dockerfile parse error: ${message}`+ : `Dockerfile parse error on line ${line}: ${message}`+ )+ this.name = 'DockerfileSyntaxError'+ }+}++const DEFAULT_ESCAPE_TOKEN = '\\'++function withLine<T>(line: number, fn: () => T): T {+ try {+ return fn()+ } catch (err) {+ if (err instanceof DockerfileSyntaxError) {+ throw err+ }+ throw new DockerfileSyntaxError(+ err instanceof Error ? err.message : String(err),+ line+ )+ }+}+const WHITESPACE = /[\t\v\f\r ]+/+const DIRECTIVE = /^#\s*([a-zA-Z][a-zA-Z0-9]*)\s*=\s*(.+?)\s*$/+const VALID_DIRECTIVES = new Set(['syntax', 'escape', 'check'])+const HEREDOC_INSTRUCTIONS = new Set(['ADD', 'COPY', 'RUN'])++type LineParser = (+ rest: string,+ escapeToken: string+) => { args: string[]; json: boolean }++function trimNewline(line: string): string {+ let end = line.length+ while (end > 0 && (line[end - 1] === '\n' || line[end - 1] === '\r')) {+ end--+ }+ return line.slice(0, end)+}++function trimLeadingWhitespace(line: string): string {+ return line.replace(/^[\t\n\v\f\r \u0085\u00a0\p{Z}]+/u, '')+}++function isComment(line: string): boolean {+ return trimLeadingWhitespace(line).startsWith('#')+}++function escapeRegExp(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+}++/** Split into lines the way a `bufio.Scanner` with newline-preserving split does. */+function splitLines(content: string): string[] {+ return content.match(/[^\n]*\n|[^\n]+$/g) ?? []+}++class Directives {+ escapeToken = DEFAULT_ESCAPE_TOKEN+ private continuation = this.buildContinuationRegex(DEFAULT_ESCAPE_TOKEN)+ private done = false+ private seen = new Set<string>()++ /** Returns `true` when the line was a parser directive. */+ possibleParserDirective(line: string): boolean {+ if (this.done) {+ return false+ }+ const match = DIRECTIVE.exec(line)+ if (!match) {+ this.done = true+ return false+ }+ const key = match[1].toLowerCase()+ if (!VALID_DIRECTIVES.has(key)) {+ this.done = true+ return false+ }+ if (this.seen.has(key)) {+ throw new Error(`only one ${key} parser directive can be used`)+ }+ this.seen.add(key)+ if (key === 'escape') {+ this.setEscapeToken(match[2])+ }+ return true+ }++ trimContinuation(line: string): { line: string; isEndOfLine: boolean } {+ if (this.continuation.test(line)) {+ return { line: line.replace(this.continuation, '$1'), isEndOfLine: false }+ }+ return { line, isEndOfLine: true }+ }++ private setEscapeToken(token: string) {+ if (token !== '`' && token !== '\\') {+ throw new Error(`invalid escape token '${token}' does not match \` or \\`)+ }+ this.escapeToken = token+ this.continuation = this.buildContinuationRegex(token)+ }++ private buildContinuationRegex(token: string): RegExp {+ const t = escapeRegExp(token)+ // The escape token is a line continuation when it is the last+ // non-whitespace character and not itself escaped.+ return new RegExp(`([^${t}])${t}[ \\t]*$|^${t}[ \\t]*$`)+ }+}++function parseString(rest: string) {+ return { args: rest === '' ? [] : [rest], json: false }+}++function parseIgnore() {+ return { args: [], json: false }+}++function parseStringsWhitespaceDelimited(rest: string) {+ if (rest === '') {+ return { args: [], json: false }+ }+ return { args: rest.split(WHITESPACE), json: false }+}++class NotJsonArrayError extends Error {}+class NotStringArrayError extends Error {}++function parseJSON(rest: string): string[] {+ rest = trimLeadingWhitespace(rest)+ if (!rest.startsWith('[')) {+ throw new NotJsonArrayError()+ }+ let parsed: unknown+ try {+ parsed = JSON.parse(rest)+ } catch (err) {+ throw new NotJsonArrayError()+ }+ if (!Array.isArray(parsed)) {+ throw new NotJsonArrayError()+ }+ for (const item of parsed) {+ if (typeof item !== 'string') {+ throw new NotStringArrayError('Only strings are supported in JSON arrays')+ }+ }+ return parsed as string[]+}++function parseMaybeJSON(rest: string) {+ if (rest === '') {+ return { args: [], json: false }+ }+ try {+ return { args: parseJSON(rest), json: true }+ } catch (err) {+ if (err instanceof NotStringArrayError) {+ throw err+ }+ return { args: [rest], json: false }+ }+}++// `HEALTHCHECK [flags] <type> <command>`: the type (`CMD`/`NONE`) is the first+// argument, the command follows in JSON or shell form+function parseHealthConfig(rest: string) {+ const chars = Array.from(rest)+ let sep = 0+ while (sep < chars.length && !isSpace(chars[sep])) {+ sep+++ }+ let next = sep+ while (next < chars.length && isSpace(chars[next])) {+ next+++ }+ if (sep === 0) {+ return { args: [], json: false }+ }+ const { args, json } = parseMaybeJSON(chars.slice(next).join(''))+ return { args: [chars.slice(0, sep).join(''), ...args], json }+}++function parseMaybeJSONToList(rest: string) {+ try {+ return { args: parseJSON(rest), json: true }+ } catch (err) {+ if (err instanceof NotStringArrayError) {+ throw err+ }+ return parseStringsWhitespaceDelimited(rest)+ }+}++/**+ * Split a line into whitespace separated words, keeping quotes and escape+ * characters in place (they are resolved later by the shell lexer).+ */+export function parseWords(rest: string, escapeToken: string): string[] {+ const chars = Array.from(rest)+ const words: string[] = []+ let phase: 'spaces' | 'word' | 'quote' = 'spaces'+ let quote = ''+ let blankOK = false+ let word = ''++ for (let pos = 0; pos <= chars.length; pos++) {+ const ch = chars[pos]++ if (phase === 'spaces') {+ if (pos === chars.length) {+ break+ }+ if (isSpace(ch)) {+ continue+ }+ phase = 'word'+ }+ if (pos === chars.length) {+ if (blankOK || word.length > 0) {+ words.push(word)+ }+ break+ }+ if (phase === 'word') {+ if (isSpace(ch)) {+ phase = 'spaces'+ if (blankOK || word.length > 0) {+ words.push(word)+ }+ word = ''+ blankOK = false+ continue+ }+ if (ch === "'" || ch === '"') {+ quote = ch+ blankOK = true+ phase = 'quote'+ }+ if (ch === escapeToken) {+ if (pos + 1 === chars.length) {+ continue // skip an escape token at end of line+ }+ // outside quotes an escape token always keeps itself and the+ // following character, even if that character is a quote+ word += ch+ pos+++ word += chars[pos]+ continue+ }+ word += ch+ continue+ }+ // phase === 'quote'+ if (ch === quote) {+ phase = 'word'+ }+ if (ch === escapeToken && quote !== "'") {+ if (pos + 1 === chars.length) {+ phase = 'word'+ continue // skip the escape token at end+ }+ word += ch+ pos+++ word += chars[pos]+ continue+ }+ word += ch+ }++ return words+}++/**+ * Like `parseMaybeJSONToList`, but the shell form is split with quote+ * awareness so that `COPY "my file.txt" /dest/` works (Docker only+ * supports such paths in JSON form).+ */+function parseMaybeJSONToWords(rest: string, escapeToken: string) {+ try {+ return { args: parseJSON(rest), json: true }+ } catch (err) {+ if (err instanceof NotStringArrayError) {+ throw err+ }+ return { args: parseWords(rest, escapeToken), json: false }+ }+}++function parseNameOrNameVal(rest: string, escapeToken: string) {+ return { args: parseWords(rest, escapeToken), json: false }+}++function parseNameVal(key: string): LineParser {+ return (rest, escapeToken) => {+ const words = parseWords(rest, escapeToken)+ if (words.length === 0) {+ return { args: [], json: false }+ }++ // Old format: KEY name value+ if (!words[0].includes('=')) {+ const match = WHITESPACE.exec(rest)+ if (!match) {+ throw new Error(`${key} must have two arguments`)+ }+ const name = rest.slice(0, match.index)+ const value = rest.slice(match.index + match[0].length)+ return { args: [name, value, ''], json: false }+ }++ const args: string[] = []+ for (const word of words) {+ if (!word.includes('=')) {+ throw new Error(+ `Syntax error - can't find = in "${word}". Must be of the form: name=value`+ )+ }+ const index = word.indexOf('=')+ args.push(word.slice(0, index), word.slice(index + 1), '=')+ }+ return { args, json: false }+ }+}++const LINE_PARSERS: Record<string, LineParser> = {+ ADD: parseMaybeJSONToWords,+ ARG: parseNameOrNameVal,+ CMD: parseMaybeJSON,+ COPY: parseMaybeJSONToWords,+ ENTRYPOINT: parseMaybeJSON,+ ENV: parseNameVal('ENV'),+ EXPOSE: parseStringsWhitespaceDelimited,+ FROM: parseStringsWhitespaceDelimited,+ HEALTHCHECK: parseHealthConfig,+ LABEL: parseNameVal('LABEL'),+ MAINTAINER: parseString,+ ONBUILD: parseIgnore,+ RUN: parseMaybeJSON,+ SHELL: parseMaybeJSON,+ STOPSIGNAL: parseString,+ USER: parseString,+ VOLUME: parseMaybeJSONToList,+ WORKDIR: parseString,+}++/** Parses leading `--flag[=value]` words. Returns the remaining line and flags. */+function extractBuilderFlags(+ line: string,+ escapeToken: string+): { rest: string; flags: string[] } {+ const chars = Array.from(line)+ const flags: string[] = []+ let phase: 'spaces' | 'word' | 'quote' = 'spaces'+ let quote = ''+ let blankOK = false+ let word = ''++ for (let pos = 0; pos <= chars.length; pos++) {+ const ch = chars[pos]++ if (phase === 'spaces') {+ if (pos === chars.length) {+ break+ }+ if (isSpace(ch)) {+ continue+ }+ // only keep going if the next word starts with --+ if (ch !== '-' || pos + 1 === chars.length || chars[pos + 1] !== '-') {+ return { rest: chars.slice(pos).join(''), flags }+ }+ phase = 'word'+ }+ if (pos === chars.length) {+ if (word !== '--' && (blankOK || word.length > 0)) {+ flags.push(word)+ }+ break+ }+ if (phase === 'word') {+ if (isSpace(ch)) {+ phase = 'spaces'+ if (word === '--') {+ return { rest: chars.slice(pos).join(''), flags }+ }+ if (blankOK || word.length > 0) {+ flags.push(word)+ }+ word = ''+ blankOK = false+ continue+ }+ if (ch === "'" || ch === '"') {+ quote = ch+ blankOK = true+ phase = 'quote'+ continue+ }+ if (ch === escapeToken) {+ if (pos + 1 === chars.length) {+ continue+ }+ pos+++ word += chars[pos]+ continue+ }+ word += ch+ continue+ }+ // phase === 'quote'+ if (ch === quote) {+ phase = 'word'+ continue+ }+ if (ch === escapeToken) {+ if (pos + 1 === chars.length) {+ phase = 'word'+ continue+ }+ pos+++ word += chars[pos]+ continue+ }+ word += ch+ }++ return { rest: '', flags }+}++function splitCommand(+ line: string,+ escapeToken: string+): { command: string; flags: string[]; rest: string } {+ const trimmed = line.trim()+ const match = WHITESPACE.exec(trimmed)+ if (!match) {+ return { command: trimmed, flags: [], rest: '' }+ }+ const command = trimmed.slice(0, match.index)+ const { rest, flags } = extractBuilderFlags(+ trimmed.slice(match.index + match[0].length),+ escapeToken+ )+ return { command, flags, rest: rest.trim() }+}++// Matches `^(\d*)<<(-?)\s*([^<]*)$` without a regex, whose adjacent `\s*`+// and `[^<]*` are ambiguous on whitespace runs (polynomial backtracking).+const HEREDOC_SPACES = '\t\n\f\r '++function matchHeredocMarker(+ word: string+): { fileDescriptor: string; chomp: boolean; rest: string } | undefined {+ let i = 0+ while (i < word.length && word[i] >= '0' && word[i] <= '9') {+ i+++ }+ if (!word.startsWith('<<', i)) {+ return undefined+ }+ const fileDescriptor = word.slice(0, i)+ i += 2+ const chomp = word[i] === '-'+ if (chomp) {+ i+++ }+ while (i < word.length && HEREDOC_SPACES.includes(word[i])) {+ i+++ }+ const rest = word.slice(i)+ if (rest.includes('<')) {+ return undefined+ }+ return { fileDescriptor, chomp, rest }+}++export function parseHeredoc(word: string): DockerfileHeredoc | undefined {+ const match = matchHeredocMarker(word)+ if (!match) {+ return undefined+ }+ const fileDescriptor =+ match.fileDescriptor === '' ? 0 : parseInt(match.fileDescriptor, 10)+ const { chomp, rest } = match+ if (rest.length === 0) {+ return undefined+ }++ // Lex the terminator both with and without quotes. If the results+ // differ, part of the word was quoted and the content must not expand.+ const words = new ShellLex('\\').processWords(rest)+ if (words.length !== 1) {+ return undefined+ }+ const wordsRaw = new ShellLex('\\', { rawQuotes: true }).processWords(rest)+ if (wordsRaw.length !== words.length) {+ throw new Error(+ `internal lexing of heredoc produced inconsistent results: ${rest}`+ )+ }++ const countQuotes = (s: string) =>+ (s.match(/'/g) ?? []).length + (s.match(/"/g) ?? []).length+ const expand = countQuotes(words[0]) === countQuotes(wordsRaw[0])++ return { name: words[0], content: '', chomp, expand, fileDescriptor }+}++function heredocsFromLine(line: string): DockerfileHeredoc[] {+ let words: string[]+ try {+ words = new ShellLex('\\', {+ rawQuotes: true,+ rawEscapes: true,+ }).processWords(line)+ } catch {+ return []+ }+ const heredocs: DockerfileHeredoc[] = []+ for (const word of words) {+ const heredoc = parseHeredoc(word)+ if (heredoc) {+ heredocs.push(heredoc)+ }+ }+ return heredocs+}++/** Strips leading tabs from every line (`<<-` heredocs). */+export function chompHeredocContent(content: string): string {+ return content.replace(/^\t+/gm, '')+}++export function parseDockerfileAst(content: string): DockerfileAst {+ const directives = new Directives()+ const lines = splitLines(content.replace(/^\uFEFF/, ''))+ const instructions: DockerfileInstruction[] = []+ const warnings: DockerfileWarning[] = []++ let currentLine = 0+ let index = 0++ const processLine = (raw: string, stripLeftWhitespace: boolean): string => {+ let line = trimNewline(raw)+ if (stripLeftWhitespace) {+ line = trimLeadingWhitespace(line)+ }+ withLine(currentLine + 1, () => directives.possibleParserDirective(line))+ return isComment(line) ? '' : line+ }++ while (index < lines.length) {+ const raw = lines[index++]+ let line = processLine(raw, true)+ currentLine+++ const startLine = currentLine++ const first = directives.trimContinuation(line)+ line = first.line+ let isEndOfLine = first.isEndOfLine+ if (isEndOfLine && line.length === 0) {+ continue+ }++ let hasEmptyContinuationLine = false+ while (!isEndOfLine && index < lines.length) {+ const continuationRaw = lines[index++]+ const continuation = processLine(continuationRaw, false)+ currentLine++++ if (isComment(continuationRaw)) {+ continue+ }+ if (trimLeadingWhitespace(trimNewline(continuationRaw)).length === 0) {+ hasEmptyContinuationLine = true+ continue+ }++ const trimmed = directives.trimContinuation(continuation)+ isEndOfLine = trimmed.isEndOfLine+ line += trimmed.line+ }++ if (hasEmptyContinuationLine) {+ warnings.push({+ message: `Empty continuation line found in: ${line}`,+ line: currentLine,+ })+ }++ const { command, flags, rest } = splitCommand(line, directives.escapeToken)+ const name = command.toUpperCase()+ const lineParser = LINE_PARSERS[name]+ if (!lineParser) {+ throw new DockerfileSyntaxError(+ `unknown instruction: ${command}`,+ startLine+ )+ }++ const parsed = withLine(startLine, () =>+ lineParser(rest, directives.escapeToken)+ )++ const instruction: DockerfileInstruction = {+ name,+ original: line,+ flags,+ args: parsed.args,+ json: parsed.json,+ heredocs: [],+ startLine,+ endLine: currentLine,+ }++ if (HEREDOC_INSTRUCTIONS.has(name) && !parsed.json && line.includes('<<')) {+ const heredocs = withLine(startLine, () => heredocsFromLine(line))+ for (const heredoc of heredocs) {+ let terminated = false+ while (index < lines.length) {+ const heredocLine = lines[index++]+ currentLine++++ let possibleTerminator = trimNewline(heredocLine)+ if (heredoc.chomp) {+ possibleTerminator = possibleTerminator.replace(/^\t+/, '')+ }+ if (possibleTerminator === heredoc.name) {+ terminated = true+ break+ }+ heredoc.content += heredocLine+ }+ if (!terminated) {+ throw new DockerfileSyntaxError('unterminated heredoc', startLine)+ }+ instruction.heredocs.push(heredoc)+ }+ instruction.endLine = currentLine+ }++ instructions.push(instruction)+ }++ return { instructions, escapeToken: directives.escapeToken, warnings }+}diff --git a/packages/dockerfile-utils-js/tests/buildkit-parser.test.ts b/packages/dockerfile-utils-js/tests/buildkit-parser.test.tsnew file mode 100644index 000000000..5632e5a99--- /dev/null+++ b/packages/dockerfile-utils-js/tests/buildkit-parser.test.ts@@ -0,0 +1,472 @@+import { readdirSync, readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { assert, describe, test } from 'vitest'++import {+ chompHeredocContent,+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileSyntaxError,+ parseDockerfileAst,+ parseHeredoc,+ parseWords,+} from '../src'++// Port of BuildKit's `frontend/dockerfile/parser` tests, see+// `fixtures/buildkit/README.md`.++const FIXTURES = fileURLToPath(+ new URL('./fixtures/buildkit/parser/', import.meta.url)+)++function read(...parts: string[]): string {+ return readFileSync(FIXTURES + parts.join('/'), 'utf-8')+}++const PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S} ]$/u++/** `strconv.Quote` */+function goQuote(s: string): string {+ let out = '"'+ for (const ch of s) {+ switch (ch) {+ case '"':+ out += '\\"'+ break+ case '\\':+ out += '\\\\'+ break+ case '\x07':+ out += '\\a'+ break+ case '\b':+ out += '\\b'+ break+ case '\f':+ out += '\\f'+ break+ case '\n':+ out += '\\n'+ break+ case '\r':+ out += '\\r'+ break+ case '\t':+ out += '\\t'+ break+ case '\v':+ out += '\\v'+ break+ default: {+ if (PRINTABLE.test(ch)) {+ out += ch+ break+ }+ const cp = ch.codePointAt(0) as number+ if (cp < 0x80) {+ out += '\\x' + cp.toString(16).padStart(2, '0')+ } else if (cp < 0x10000) {+ out += '\\u' + cp.toString(16).padStart(4, '0')+ } else {+ out += '\\U' + cp.toString(16).padStart(8, '0')+ }+ }+ }+ }+ return out + '"'+}++/** The flat equivalent of BuildKit's `Node.Dump()` */+function dump(instruction: DockerfileInstruction): string {+ let str = instruction.name.toLowerCase()+ if (instruction.flags.length > 0) {+ str += ` [${instruction.flags.map(goQuote).join(' ')}]`+ }+ if (instruction.name === 'ONBUILD') {+ // BuildKit parses the trigger as a child node+ const rest = instruction.original.replace(/^\S+\s*/, '')+ const [child] = parseDockerfileAst(rest).instructions+ return `(${str} ${dump(child)})`+ }+ for (const arg of instruction.args) {+ str += ' ' + goQuote(arg)+ }+ return `(${str})`+}++function dumpAll(content: string): string {+ return parseDockerfileAst(content).instructions.map(dump).join('\n')+}++describe('BuildKit parser', () => {+ describe('TestParseCases (testfiles)', () => {+ const dirs = readdirSync(FIXTURES + 'testfiles').sort()+ // BuildKit splits shell-form ADD/COPY on whitespace only, this parser+ // honors quotes so `COPY "a b" /dst` works, which changes the result for+ // the unbalanced `ADD \conf\\" /.znc`+ const deviations = new Set(['escapes'])+ test.for(dirs)('%s', (dir, { skip }) => {+ skip(deviations.has(dir), 'ADD/COPY words are quote-aware here')+ const dockerfile = read('testfiles', dir, 'Dockerfile')+ const expected = read('testfiles', dir, 'result')+ assert.strictEqual(dumpAll(dockerfile), expected.trim())+ })+ })++ describe('TestParseErrorCases (testfiles-negative)', () => {+ const dirs = readdirSync(FIXTURES + 'testfiles-negative').sort()+ // BuildKit reports "file with no instructions" for these; an empty+ // instruction list is returned here instead+ const empty = new Set(['empty_dockerfile', 'only_comments'])+ test.each(dirs)('%s', (dir) => {+ const dockerfile = read('testfiles-negative', dir, 'Dockerfile')+ if (empty.has(dir)) {+ assert.deepEqual(parseDockerfileAst(dockerfile).instructions, [])+ return+ }+ assert.throws(() => parseDockerfileAst(dockerfile), DockerfileSyntaxError)+ })+ })++ test('TestParseIncludesLineNumbers', () => {+ const { instructions } = parseDockerfileAst(+ read('testfile-line/Dockerfile')+ )+ assert.lengthOf(instructions, 3)+ const lines = instructions.map((i) => [i.startLine, i.endLine])+ assert.deepEqual(lines, [+ [5, 5],+ [11, 12],+ [17, 31],+ ])+ })++ test('TestParseWarnsOnEmptyContinutationLine', () => {+ const dockerfile = `+FROM alpine:3.6++RUN valid \\+ continuation++RUN something \\++ following \\++ more++RUN another \\++ thing++RUN non-indented \\+# this is a comment+ after-comment++RUN indented \\+ # this is an indented comment+ comment+\t`+ const { warnings } = parseDockerfileAst(dockerfile)+ assert.lengthOf(warnings, 2)+ assert.include(warnings[0].message, 'Empty continuation line found in')+ assert.include(warnings[0].message, 'RUN something following more')+ assert.include(warnings[1].message, 'RUN another thing')+ })++ test('TestParseWords', () => {+ const tests: [string, string[]][] = [+ ['foo', ['foo']],+ ['foo bar', ['foo', 'bar']],+ ['foo\\ bar', ['foo\\ bar']],+ ['foo=bar', ['foo=bar']],+ ["foo bar 'abc xyz'", ['foo', 'bar', "'abc xyz'"]],+ ['foo bar "abc xyz"', ['foo', 'bar', '"abc xyz"']],+ ['àöû', ['àöû']],+ ['föo bàr "âbc xÿz"', ['föo', 'bàr', '"âbc xÿz"']],+ ]+ for (const [input, expected] of tests) {+ assert.deepEqual(parseWords(input, '\\'), expected)+ }+ })++ describe('TestJSONArraysOfStrings', () => {+ const valid: [string, string[]][] = [+ ['[]', []],+ ['[""]', ['']],+ ['["a"]', ['a']],+ ['["a","b"]', ['a', 'b']],+ ['[ "a", "b" ]', ['a', 'b']],+ ['[\t"a",\t"b"\t]', ['a', 'b']],+ ['\t[\t"a",\t"b"\t]\t', ['a', 'b']],+ [+ '["abc 123", "♥", "☃", "\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u0000"]',+ ['abc 123', '♥', '☃', '" \\ / \b \f \n \r \t \u0000'],+ ],+ ]+ const invalid = [+ '["a",42,"b"]',+ '["a",123.456,"b"]',+ '["a",{},"b"]',+ '["a",{"c": "d"},"b"]',+ '["a",["c"],"b"]',+ '["a",true,"b"]',+ '["a",false,"b"]',+ '["a",null,"b"]',+ ]++ test.each(valid)('%j', (json, expected) => {+ const [run] = parseDockerfileAst(`RUN ${json}`).instructions+ assert.isTrue(run.json)+ assert.deepEqual(run.args, expected)+ })++ test.each(invalid)('%j', (json) => {+ assert.throws(+ () => parseDockerfileAst(`RUN ${json}`),+ 'Only strings are supported in JSON arrays'+ )+ })+ })++ test('TestParseNameValOldFormat', () => {+ const [label] = parseDockerfileAst('LABEL foo bar').instructions+ assert.deepEqual(label.args, ['foo', 'bar', ''])+ })++ test('TestParseNameValNewFormat', () => {+ const [label] = parseDockerfileAst('LABEL foo=bar thing=star').instructions+ assert.deepEqual(label.args, ['foo', 'bar', '=', 'thing', 'star', '='])+ })++ test('TestParseNameValWithoutVal', () => {+ assert.throws(+ () => parseDockerfileAst('ENV foo'),+ 'ENV must have two arguments'+ )+ })++ test('TestParseExtractsHeredoc', () => {+ // The upstream file has an `INVALID` line after `USER <<INVALID`, which+ // this parser rejects as an unknown instruction+ const dockerfile = `+FROM alpine:3.6+ENV NAME=me+RUN ls+USER <<INVALID+RUN <<EMPTY+EMPTY+RUN 3<<EMPTY2+EMPTY2+RUN "<<NOHEREDOC"+RUN <<INDENT+\tfoo+\tbar+INDENT+RUN <<-UNINDENT+\tbaz+\tquux+UNINDENT+RUN <<-UNINDENT2+\tbaz+\tquux+\tUNINDENT2+RUN <<-EXPAND+\texpand $NAME+EXPAND+RUN <<-'NOEXPAND'+\tdon't expand $NAME+NOEXPAND+RUN <<COPY+echo hello world+echo foo bar+COPY+RUN <<COMMENT+# internal comment+echo hello world+echo foo bar # trailing comment+COMMENT+RUN --mount=type=cache,target=/foo <<MOUNT+echo hello+MOUNT+COPY <<FILE1 <<FILE2 /dest+content 1+FILE1+content 2+FILE2+COPY <<EOF /quotes+"foo"+'bar'+EOF+COPY <<X <<Y /dest+Y+X+X+Y+RUN <<COMPLEX python3+print('hello world')+COMPLEX+COPY <<file.txt /dest+hello world+file.txt+RUN <<eo'f'+echo foo+eof+RUN <<eo\\'f+echo foo+eo'f+RUN <<'e'o\\'f+echo foo+eo'f+RUN <<'one two'+echo bar+one two+RUN <<$EOF+$EOF+RUN << EOF+EOF+RUN << EOF > foo+EOF+\t`+ const heredoc = (+ name: string,+ content: string,+ options: Partial<DockerfileHeredoc> = {}+ ): DockerfileHeredoc => ({+ name,+ content,+ chomp: false,+ expand: true,+ fileDescriptor: 0,+ ...options,+ })+ const tests: DockerfileHeredoc[][] = [+ [], // ENV EXAMPLE=bla+ [], // RUN ls+ [], // USER <<INVALID+ [heredoc('EMPTY', '')],+ [heredoc('EMPTY2', '', { fileDescriptor: 3 })],+ [], // RUN "<<NOHEREDOC"+ [heredoc('INDENT', '\tfoo\n\tbar\n')],+ [heredoc('UNINDENT', '\tbaz\n\tquux\n', { chomp: true })],+ [heredoc('UNINDENT2', '\tbaz\n\tquux\n', { chomp: true })],+ [heredoc('EXPAND', '\texpand $NAME\n', { chomp: true })],+ [+ heredoc('NOEXPAND', "\tdon't expand $NAME\n", {+ chomp: true,+ expand: false,+ }),+ ],+ [heredoc('COPY', 'echo hello world\necho foo bar\n')],+ [+ heredoc(+ 'COMMENT',+ '# internal comment\necho hello world\necho foo bar # trailing comment\n'+ ),+ ],+ [heredoc('MOUNT', 'echo hello\n')],+ [heredoc('FILE1', 'content 1\n'), heredoc('FILE2', 'content 2\n')],+ [heredoc('EOF', '"foo"\n\'bar\'\n')],+ [heredoc('X', 'Y\n'), heredoc('Y', 'X\n')],+ [heredoc('COMPLEX', "print('hello world')\n")],+ [heredoc('file.txt', 'hello world\n')],+ [heredoc('eof', 'echo foo\n', { expand: false })],+ [heredoc("eo'f", 'echo foo\n')],+ [heredoc("eo'f", 'echo foo\n', { expand: false })],+ [heredoc('one two', 'echo bar\n', { expand: false })],+ [heredoc('$EOF', '')],+ [heredoc('EOF', '')],+ [heredoc('EOF', '')],+ ]+ const { instructions } = parseDockerfileAst(dockerfile)+ assert.lengthOf(instructions, tests.length + 1)+ tests.forEach((expected, i) => {+ assert.deepEqual(instructions[i + 1].heredocs, expected)+ })+ })++ test('TestParseJSONHeredoc', () => {+ const dockerfile = `+FROM alpine:3.6+RUN ["whoami"]+RUN ["<<EOF"]+RUN ["<<'EOF'"]+\t`+ const { instructions } = parseDockerfileAst(dockerfile)+ for (let i = 1; i <= 3; i++) {+ assert.deepEqual(instructions[i].heredocs, [])+ }+ })++ test('TestHeredocChomp', () => {+ assert.strictEqual(+ chompHeredocContent('\thello\n\tworld\n'),+ 'hello\nworld\n'+ )+ })++ test('TestParseHeredocHelpers', () => {+ const validHeredocs = [+ '<<EOF',+ "<<'EOF'",+ '<<"EOF"',+ '<<-EOF',+ "<<-'EOF'",+ '<<-"EOF"',+ '<<EO"F"',+ '<< EOF',+ '<<- EOF',+ ]+ const invalidHeredocs = ["<<'EOF", '<<"EOF', "<<EOF'", '<<EOF"']+ const notHeredocs = ['', 'EOF', '<<', '<<-', '<EOF', '<<<EOF', '<<EOF sh']++ for (const src of notHeredocs) {+ assert.isUndefined(parseHeredoc(src), src)+ }+ for (const src of validHeredocs) {+ assert.strictEqual(parseHeredoc(src)?.name, 'EOF', src)+ }+ for (const src of invalidHeredocs) {+ assert.throws(() => parseHeredoc(src), undefined, undefined, src)+ }+ })++ test('TestHeredocsFromLine', () => {+ const srcs: [string, string[]][] = [+ ['RUN <<EOF', ['EOF']],+ ['RUN <<-EOF', ['EOF']],+ ['RUN <<EOF', ['EOF']],+ // upstream expects `EOF` here, but only asserts over the heredocs that+ // were found and BuildKit's lexer splits `<<-` and `EOF` into two words+ ['RUN <<- EOF', []],+ ['RUN << -EOF', ['-EOF']],+ ["RUN <<'EOF'", ['EOF']],+ ['RUN 4<<EOF', ['EOF']],+ ['RUN <<EOF <<EOF2', ['EOF', 'EOF2']],+ ["RUN '<<EOF'", []],+ ['RUN "<<EOF"', []],+ ]+ for (const [line, names] of srcs) {+ const dockerfile = [line, ...names, ''].join('\n')+ const [run] = parseDockerfileAst(dockerfile).instructions+ assert.deepEqual(+ run.heredocs.map((h) => h.name),+ names,+ line+ )+ }+ })++ describe('directives', () => {+ test('TestParser (escape directive)', () => {+ const { escapeToken } = parseDockerfileAst(+ '#escape=\\\n# key = FOO bar\nFROM x'+ )+ assert.strictEqual(escapeToken, '\\')+ })++ test('TestParserEscapeCaseInsensitive', () => {+ const { escapeToken } = parseDockerfileAst('# EScape=`\nFROM x')+ assert.strictEqual(escapeToken, '`')+ })+ })+})diff --git a/packages/dockerfile-utils-js/tests/buildkit-shell.test.ts b/packages/dockerfile-utils-js/tests/buildkit-shell.test.tsnew file mode 100644index 000000000..a6e06ac8f--- /dev/null+++ b/packages/dockerfile-utils-js/tests/buildkit-shell.test.ts@@ -0,0 +1,155 @@+import { readFileSync } from 'node:fs'+import { assert, describe, test } from 'vitest'++import { ShellLex } from '../src'++// BuildKit's `frontend/dockerfile/shell` word tables, see+// `fixtures/buildkit/README.md` for how the expectations were generated.++interface LexCase {+ input: string+ word: string | null+ words: string[]+ error?: boolean+}++interface EnvCase {+ input: string+ env: Record<string, string>+ word?: string+ words?: string[]+ error?: boolean+}++function loadCases<T = LexCase>(name: string): T[] {+ const url = new URL(`./fixtures/buildkit/shell/${name}.json`, import.meta.url)+ return JSON.parse(readFileSync(url, 'utf-8')) as T[]+}++function check(cases: LexCase[], rawQuotes: boolean) {+ test.each(cases)('$input', ({ input, word, words, error }) => {+ const lex = new ShellLex('\\', { rawQuotes })+ if (error) {+ assert.throws(() => lex.processWord(input))+ assert.throws(() => lex.processWords(input))+ return+ }+ assert.strictEqual(lex.processWord(input), word)+ assert.deepEqual(lex.processWords(input), words)+ })+}++describe('BuildKit shell lexer tables', () => {+ describe('wordsTest', () => {+ check(loadCases('wordsTest'), false)+ })++ describe('wordsTest (RawQuotes)', () => {+ check(loadCases('wordsTest.rawQuotes'), true)+ })++ describe('envVarTest', () => {+ check(loadCases('envVarTest'), false)+ })++ describe('envVarTest (expanded)', () => {+ const env = new Map([+ ['PWD', '/home'],+ ['SHELL', 'bash'],+ ['KOREAN', '한국어'],+ ['NULL', ''],+ ])+ const lex = new ShellLex('\\', { env, skipUnsetEnv: false })+ test.each(loadCases('envVarTest.env'))(+ '$input',+ ({ input, word, error }) => {+ if (error) {+ assert.throws(() => lex.processWord(input))+ return+ }+ assert.strictEqual(lex.processWord(input), word)+ }+ )+ })++ // TestShellParser4Words with the `ENV` lines of `wordsTest` applied+ // cumulatively. Upstream also loops a RawQuotes + SkipUnsetEnv mode, but it+ // re-scans the already exhausted file, so only the normal mode is asserted.+ describe('wordsTest with ENV', () => {+ test.each(loadCases<EnvCase>('wordsTest.env'))(+ '$input',+ ({ input, env, words, error }) => {+ const lex = new ShellLex('\\', {+ env: new Map(Object.entries(env)),+ skipUnsetEnv: false,+ })+ if (error) {+ assert.throws(() => lex.processWords(input))+ return+ }+ assert.deepEqual(lex.processWords(input), words)+ }+ )+ })++ describe('TestProcessWithMatches', () => {+ test.each(loadCases<EnvCase>('processWithMatches'))(+ '$input',+ ({ input, env, word, error }) => {+ const lex = new ShellLex('\\', {+ env: new Map(Object.entries(env)),+ skipUnsetEnv: false,+ })+ if (error) {+ assert.throws(() => lex.processWord(input))+ return+ }+ assert.strictEqual(lex.processWord(input), word)+ }+ )+ })++ test('TestProcessWithMatchesPlatform', () => {+ const release =+ 'something-${VERSION}.${TARGETOS}-${TARGETARCH}${TARGETVARIANT:+-${TARGETVARIANT}}.tar.gz'+ const run = (env: Record<string, string>) =>+ new ShellLex('\\', {+ env: new Map(Object.entries(env)),+ skipUnsetEnv: false,+ }).processWord(release)+ const base = { VERSION: 'v1.2.3', TARGETOS: 'linux' }+ assert.equal(+ run({ ...base, TARGETARCH: 'arm', TARGETVARIANT: 'v7' }),+ 'something-v1.2.3.linux-arm-v7.tar.gz'+ )+ assert.equal(+ run({ ...base, TARGETARCH: 'arm64', TARGETVARIANT: '' }),+ 'something-v1.2.3.linux-arm64.tar.gz'+ )+ assert.equal(+ run({ ...base, TARGETARCH: 'arm64' }),+ 'something-v1.2.3.linux-arm64.tar.gz'+ )+ })++ test('TestShellParserMandatoryEnvVars', () => {+ const run = (word: string, env: Record<string, string>) =>+ new ShellLex('\\', {+ env: new Map(Object.entries(env)),+ skipUnsetEnv: false,+ }).processWord(word)+ const set = { VAR: 'plain', ARG: 'x' }+ const empty = { VAR: '', ARG: 'x' }+ const unset = { ARG: 'x' }+ const noEmpty = '${VAR:?message here$ARG}'+ const noUnset = '${VAR?message here$ARG}'++ assert.equal(run(noEmpty, set), 'plain')+ assert.throws(() => run(noEmpty, empty), /message herex/)+ assert.throws(() => run(noEmpty, unset), /message herex/)++ assert.equal(run(noUnset, set), 'plain')+ assert.equal(run(noUnset, empty), '')+ assert.throws(() => run(noUnset, unset), /message herex/)+ })+})diff --git a/packages/dockerfile-utils-js/tests/dockerignore.test.ts b/packages/dockerfile-utils-js/tests/dockerignore.test.tsnew file mode 100644index 000000000..c778e6025--- /dev/null+++ b/packages/dockerfile-utils-js/tests/dockerignore.test.ts@@ -0,0 +1,86 @@+import { assert, test } from 'vitest'++import { PatternMatcher } from '../src'++test('matches like .dockerignore', () => {+ const matcher = new PatternMatcher([+ '# comment',+ '',+ 'node_modules',+ '/dist/',+ '*.log',+ '**/*.tmp',+ 'docs/**',+ '!docs/README.md',+ 'src/[a-c]?.ts',+ ])++ assert.isTrue(matcher.matches('node_modules'))+ assert.isTrue(matcher.matches('node_modules/pkg/index.js'))+ assert.isFalse(matcher.matches('src/node_modules'))+ assert.isTrue(matcher.matches('dist'))+ assert.isTrue(matcher.matches('dist/index.js'))+ assert.isTrue(matcher.matches('app.log'))+ assert.isFalse(matcher.matches('logs/app.log'))+ assert.isTrue(matcher.matches('a/b/c.tmp'))+ assert.isTrue(matcher.matches('docs/guide/intro.md'))+ assert.isFalse(matcher.matches('docs/README.md'))+ assert.isFalse(matcher.matches('docs'))+ assert.isTrue(matcher.matches('src/a1.ts'))+ assert.isFalse(matcher.matches('src/d1.ts'))+ assert.isFalse(matcher.matches('src/index.ts'))+})++test('a parent match excludes everything under it', () => {+ const matcher = new PatternMatcher(['build', '!build/keep'])+ assert.isTrue(matcher.matches('build/out.js'))+ assert.isFalse(matcher.matches('build/keep'))+ assert.isFalse(matcher.matches('build/keep/file'))+})++test('mayMatchUnder tells whether an excluded directory must be walked', () => {+ const matcher = new PatternMatcher(['*', '!src/lib/**', '!a/b/c'])+ assert.isTrue(matcher.mayMatchUnder('src'))+ assert.isTrue(matcher.mayMatchUnder('src/lib'))+ assert.isTrue(matcher.mayMatchUnder('a/b'))+ assert.isFalse(matcher.mayMatchUnder('a/b/c'))+ assert.isFalse(matcher.mayMatchUnder('other'))+})++test('cleans patterns like filepath.Clean', () => {+ const matcher = new PatternMatcher([+ './a//b/',+ 'c/./d/../e',+ '/f/',+ '../g',+ '/../h',+ ])+ assert.isTrue(matcher.matches('a/b'))+ assert.isTrue(matcher.matches('c/e'))+ assert.isTrue(matcher.matches('f/x'))+ assert.isTrue(matcher.matches('../g'))+ assert.isTrue(matcher.matches('h'))+})++test('backslash escapes by default and separates with backslashIsSeparator', () => {+ assert.isTrue(new PatternMatcher(['a\\*b']).matches('a*b'))+ assert.isFalse(new PatternMatcher(['a\\*b']).matches('a/b'))+ const windows = new PatternMatcher(['a\\*b', 'c\\d'], {+ backslashIsSeparator: true,+ })+ assert.isTrue(windows.matches('a/xb'))+ assert.isTrue(windows.matches('c/d/e'))+})++test('rejects invalid patterns with a plain Error', () => {+ assert.throws(+ () => new PatternMatcher(['[abc']),+ Error,+ "Invalid ignore pattern '[abc'"+ )+ assert.throws(+ () => new PatternMatcher(['[\\q]']),+ Error,+ "Invalid ignore pattern '[\\q]'"+ )+})diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/README.md b/packages/dockerfile-utils-js/tests/fixtures/buildkit/README.mdnew file mode 100644index 000000000..1f267ca03--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/README.md@@ -0,0 +1,37 @@+# BuildKit test fixtures++Test data from [moby/buildkit](https://github.com/moby/buildkit) v0.26.1+(`frontend/dockerfile`, Apache License 2.0).++- `parser/`: verbatim copies of `parser/testfiles`, `parser/testfiles-negative`+ and `parser/testfile-line`. Each `result` is the `Node.Dump()` output of the+ upstream parser.+- `shell/envVarTest.env.json`: the Unix/All lines of `shell/envVarTest` with+ the upstream expectations verbatim (`TestShellParser4EnvVars`: the+ environment is `PWD=/home SHELL=bash KOREAN=한국어 NULL=`, unset variables+ expand to an empty string).+- `shell/wordsTest.env.json`: the lines of `shell/wordsTest` with the `ENV`+ lines applied cumulatively, upstream expectations verbatim+ (`TestShellParser4Words`, normal mode; unset variables expand to an empty+ string).+- `shell/processWithMatches.json`: the `TestProcessWithMatches` table from+ `shell/lex_test.go` (input, environment, expected word or error).+- `shell/`: the inputs of `shell/wordsTest` and `shell/envVarTest` with+ expectations generated by the upstream lexer in its variable-preserving+ mode (BuildKit's `SkipUnsetEnv` with an empty environment), which is how+ this lexer behaves without an `env`:++ ```go+ lex := shell.NewLex('\\')+ lex.SkipUnsetEnv = true+ lex.RawQuotes = rawQuotes // wordsTest.rawQuotes.json+ env := shell.EnvsFromSlice(nil)+ word, _, err := lex.ProcessWord(input, env)+ words, err := lex.ProcessWords(input, env)+ ```++ `ProcessWords` upstream loses the text before a `${VAR<modifier>...}`+ expression (`he${XXX:-000}xx` → `${XXX:-000}xx`): the nested+ `processStopOn` call for the modifier resets the shared words buffer. The+ `words` of those `envVarTest.json` entries are the intact words, the+ upstream output is kept as `buildkitWords`.diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfile-line/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfile-line/Dockerfilenew file mode 100644index 000000000..39184011a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfile-line/Dockerfile@@ -0,0 +1,35 @@+# ESCAPE=\++++FROM brimstone/ubuntu:14.04+++# TORUN -v /var/run/docker.sock:/var/run/docker.sock+++ENV GOPATH \+/go++++# Install the packages we need, clean up after them and us+RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+++ && apt-get --no-install-recommends install -y git golang ca-certificates \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/brimstone/consuldock \+ && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATH++++diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/empty_dockerfile/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/empty_dockerfile/Dockerfilenew file mode 100644index 000000000..e69de29bbdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfilenew file mode 100644index 000000000..1d6557879--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfile@@ -0,0 +1,3 @@+FROM busybox++ENV PATHdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfilenew file mode 100644index 000000000..5dd027a67--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfile@@ -0,0 +1,3 @@+# Hello+# These are just comments+diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfilenew file mode 100644index 000000000..d1be4596c--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfile@@ -0,0 +1 @@+CMD [ "echo", [ "nested json" ] ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfilenew file mode 100644index 000000000..035b4e8bb--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfile@@ -0,0 +1,11 @@+FROM ubuntu:14.04+LABEL maintainer Seongyeol Lim <[email protected]>++COPY . /go/src/github.com/docker/docker+ADD . /+ADD null /+COPY nullfile /tmp+ADD [ "vimrc", "/tmp" ]+COPY [ "bashrc", "/tmp" ]+COPY [ "test file", "/tmp" ]+ADD [ "test file", "/tmp/test file" ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/resultnew file mode 100644index 000000000..8468693dc--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/result@@ -0,0 +1,10 @@+(from "ubuntu:14.04")+(label "maintainer" "Seongyeol Lim <[email protected]>" "")+(copy "." "/go/src/github.com/docker/docker")+(add "." "/")+(add "null" "/")+(copy "nullfile" "/tmp")+(add "vimrc" "/tmp")+(copy "bashrc" "/tmp")+(copy "test file" "/tmp")+(add "test file" "/tmp/test file")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/Dockerfilenew file mode 100644index 000000000..6dcbdb9c2--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/Dockerfile@@ -0,0 +1,3 @@+ARG foo bar=baz+FROM ubuntu+ARG abc="123 456" defdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/resultnew file mode 100644index 000000000..90db1d5b8--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/args/result@@ -0,0 +1,3 @@+(arg "foo" "bar=baz")+(from "ubuntu")+(arg "abc=\"123 456\"" "def")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfilenew file mode 100644index 000000000..67c67f723--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfile@@ -0,0 +1,26 @@+#escape=\+FROM brimstone/ubuntu:14.04++LABEL maintainer [email protected]++# TORUN -v /var/run/docker.sock:/var/run/docker.sock++ENV GOPATH /go++# Set our command+ENTRYPOINT ["/usr/local/bin/consuldock"]++# Install the packages we need, clean up after them and us+RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y git golang ca-certificates \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/brimstone/consuldock \+ && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATHdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/resultnew file mode 100644index 000000000..3749f7c7e--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/result@@ -0,0 +1,5 @@+(from "brimstone/ubuntu:14.04")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "/go" "")+(entrypoint "/usr/local/bin/consuldock")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y git golang ca-certificates && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/brimstone/consuldock && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfilenew file mode 100644index 000000000..95c3dec9a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfile@@ -0,0 +1,52 @@+FROM brimstone/ubuntu:14.04++CMD []++ENTRYPOINT ["/usr/bin/consul", "agent", "-server", "-data-dir=/consul", "-client=0.0.0.0", "-ui-dir=/webui"]++EXPOSE 8500 8600 8400 8301 8302++RUN apt-get update \+ && apt-get --no-install-recommends install -y unzip wget \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists++RUN cd /tmp \+ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \+ -O web_ui.zip \+ && unzip web_ui.zip \+ && mv dist /webui \+ && rm web_ui.zip++RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y unzip wget \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && cd /tmp \+ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \+ -O web_ui.zip \+ && unzip web_ui.zip \+ && mv dist /webui \+ && rm web_ui.zip \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.*++ENV GOPATH /go++RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y git golang ca-certificates build-essential \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/hashicorp/consul \+ && mv $GOPATH/bin/consul /usr/bin/consul \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATHdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/resultnew file mode 100644index 000000000..168c8d61c--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/result@@ -0,0 +1,9 @@+(from "brimstone/ubuntu:14.04")+(cmd)+(entrypoint "/usr/bin/consul" "agent" "-server" "-data-dir=/consul" "-client=0.0.0.0" "-ui-dir=/webui")+(expose "8500" "8600" "8400" "8301" "8302")+(run "apt-get update && apt-get --no-install-recommends install -y unzip wget \t&& apt-get clean \t&& rm -rf /var/lib/apt/lists")+(run "cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y unzip wget && apt-get clean && rm -rf /var/lib/apt/lists && cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.*")+(env "GOPATH" "/go" "")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y git golang ca-certificates build-essential && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/hashicorp/consul \t&& mv $GOPATH/bin/consul /usr/bin/consul \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfilenew file mode 100644index 000000000..a8ec369ad--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfile@@ -0,0 +1,3 @@+FROM alpine:3.5++RUN something \\ No newline at end of filediff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/resultnew file mode 100644index 000000000..14e4f0932--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/result@@ -0,0 +1,2 @@+(from "alpine:3.5")+(run "something")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfilenew file mode 100644index 000000000..42b324e77--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfile@@ -0,0 +1,36 @@+FROM ubuntu:14.04++RUN echo hello\+ world\+ goodnight \+ moon\+ light\+ning+RUN echo hello \+ world+RUN echo hello \+world+RUN echo hello \+goodbye\+frog+RUN echo hello \+world+RUN echo hi \+ \+ world \+\+ good\+\+night+RUN echo goodbye\+frog+RUN echo good\+bye\+frog++RUN echo hello \+# this is a comment++# this is a comment with a blank line surrounding it++this is some more useful stuffdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/resultnew file mode 100644index 000000000..268ae073c--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/continueIndent/result@@ -0,0 +1,10 @@+(from "ubuntu:14.04")+(run "echo hello world goodnight moon lightning")+(run "echo hello world")+(run "echo hello world")+(run "echo hello goodbyefrog")+(run "echo hello world")+(run "echo hi world goodnight")+(run "echo goodbyefrog")+(run "echo goodbyefrog")+(run "echo hello this is some more useful stuff")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfilenew file mode 100644index 000000000..b10e67a7e--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfile@@ -0,0 +1,54 @@+FROM cpuguy83/ubuntu+ENV NAGIOS_HOME /opt/nagios+ENV NAGIOS_USER nagios+ENV NAGIOS_GROUP nagios+ENV NAGIOS_CMDUSER nagios+ENV NAGIOS_CMDGROUP nagios+ENV NAGIOSADMIN_USER nagiosadmin+ENV NAGIOSADMIN_PASS nagios+ENV APACHE_RUN_USER nagios+ENV APACHE_RUN_GROUP nagios+ENV NAGIOS_TIMEZONE UTC++RUN sed -i 's/universe/universe multiverse/' /etc/apt/sources.list+RUN apt-get update && apt-get --no-install-recommends install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx+RUN ( egrep -i "^${NAGIOS_GROUP}" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i "^${NAGIOS_CMDGROUP}" /etc/group || groupadd $NAGIOS_CMDGROUP )+RUN ( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER )++ADD http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3 /tmp/nagios.tar.gz+RUN cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf+ADD http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz /tmp/+RUN cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install++RUN sed -i.bak 's/.*\=www\-data//g' /etc/apache2/envvars+RUN export DOC_ROOT="DocumentRoot $(echo $NAGIOS_HOME/share)"; sed -i "s,DocumentRoot.*,$DOC_ROOT," /etc/apache2/sites-enabled/000-default++RUN ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo++RUN echo "use_timezone=$NAGIOS_TIMEZONE" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo "SetEnv TZ \"${NAGIOS_TIMEZONE}\"" >> /etc/apache2/conf.d/nagios.conf++RUN mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs+RUN echo "cfg_dir=${NAGIOS_HOME}/etc/conf.d" >> ${NAGIOS_HOME}/etc/nagios.cfg+RUN echo "cfg_dir=${NAGIOS_HOME}/etc/monitor" >> ${NAGIOS_HOME}/etc/nagios.cfg+RUN download-mibs && echo "mibs +ALL" > /etc/snmp/snmp.conf++RUN sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && \+ sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg+RUN cp /etc/services /var/spool/postfix/etc/++RUN mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix+ADD nagios.init /etc/sv/nagios/run+ADD apache.init /etc/sv/apache/run+ADD postfix.init /etc/sv/postfix/run+ADD postfix.stop /etc/sv/postfix/finish++ADD start.sh /usr/local/bin/start_nagios++ENV APACHE_LOCK_DIR /var/run+ENV APACHE_LOG_DIR /var/log/apache2++EXPOSE 80++VOLUME ["/opt/nagios/var", "/opt/nagios/etc", "/opt/nagios/libexec", "/var/log/apache2", "/usr/share/snmp/mibs"]++CMD ["/usr/local/bin/start_nagios"]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/resultnew file mode 100644index 000000000..f009ac681--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/result@@ -0,0 +1,40 @@+(from "cpuguy83/ubuntu")+(env "NAGIOS_HOME" "/opt/nagios" "")+(env "NAGIOS_USER" "nagios" "")+(env "NAGIOS_GROUP" "nagios" "")+(env "NAGIOS_CMDUSER" "nagios" "")+(env "NAGIOS_CMDGROUP" "nagios" "")+(env "NAGIOSADMIN_USER" "nagiosadmin" "")+(env "NAGIOSADMIN_PASS" "nagios" "")+(env "APACHE_RUN_USER" "nagios" "")+(env "APACHE_RUN_GROUP" "nagios" "")+(env "NAGIOS_TIMEZONE" "UTC" "")+(run "sed -i 's/universe/universe multiverse/' /etc/apt/sources.list")+(run "apt-get update && apt-get --no-install-recommends install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx")+(run "( egrep -i \"^${NAGIOS_GROUP}\" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i \"^${NAGIOS_CMDGROUP}\" /etc/group || groupadd $NAGIOS_CMDGROUP )")+(run "( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER )")+(add "http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3" "/tmp/nagios.tar.gz")+(run "cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf")+(add "http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz" "/tmp/")+(run "cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install")+(run "sed -i.bak 's/.*\\=www\\-data//g' /etc/apache2/envvars")+(run "export DOC_ROOT=\"DocumentRoot $(echo $NAGIOS_HOME/share)\"; sed -i \"s,DocumentRoot.*,$DOC_ROOT,\" /etc/apache2/sites-enabled/000-default")+(run "ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo")+(run "echo \"use_timezone=$NAGIOS_TIMEZONE\" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo \"SetEnv TZ \\\"${NAGIOS_TIMEZONE}\\\"\" >> /etc/apache2/conf.d/nagios.conf")+(run "mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs")+(run "echo \"cfg_dir=${NAGIOS_HOME}/etc/conf.d\" >> ${NAGIOS_HOME}/etc/nagios.cfg")+(run "echo \"cfg_dir=${NAGIOS_HOME}/etc/monitor\" >> ${NAGIOS_HOME}/etc/nagios.cfg")+(run "download-mibs && echo \"mibs +ALL\" > /etc/snmp/snmp.conf")+(run "sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg")+(run "cp /etc/services /var/spool/postfix/etc/")+(run "mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix")+(add "nagios.init" "/etc/sv/nagios/run")+(add "apache.init" "/etc/sv/apache/run")+(add "postfix.init" "/etc/sv/postfix/run")+(add "postfix.stop" "/etc/sv/postfix/finish")+(add "start.sh" "/usr/local/bin/start_nagios")+(env "APACHE_LOCK_DIR" "/var/run" "")+(env "APACHE_LOG_DIR" "/var/log/apache2" "")+(expose "80")+(volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs")+(cmd "/usr/local/bin/start_nagios")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfilenew file mode 100644index 000000000..9010bbc83--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfile@@ -0,0 +1,94 @@+# This file describes the standard way to build Docker, using docker+#+# Usage:+#+# # Assemble the full dev environment. This is slow the first time.+# docker build -t docker .+#+# # Mount your source in an interactive container for quick testing:+# docker run -v `pwd`:/go/src/github.com/docker/docker --privileged -i -t docker bash+#+# # Run the test suite:+# docker run --privileged docker hack/make.sh test-unit test-integration test-docker-py+#+# Note: AppArmor used to mess with privileged mode, but this is no longer+# the case. Therefore, you don't have to disable it anymore.+#++FROM ubuntu:14.04+LABEL maintainer Tianon Gravi <[email protected]> (@tianon)++# Packaged dependencies+RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -yq \+ apt-utils \+ aufs-tools \+ automake \+ btrfs-tools \+ build-essential \+ curl \+ dpkg-sig \+ git \+ iptables \+ libapparmor-dev \+ libcap-dev \+ mercurial \+ pandoc \+ parallel \+ reprepro \+ ruby1.9.1 \+ ruby1.9.1-dev \+ s3cmd=1.1.0* \+ --no-install-recommends++# Get lvm2 source for compiling statically+RUN git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103+# see https://git.fedorahosted.org/cgit/lvm2.git/refs/tags for release tags+# note: we don't use "git clone -b" above because it then spews big nasty warnings about 'detached HEAD' state that we can't silence as easily as we can silence them using "git checkout" directly++# Compile and install lvm2+RUN cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper+# see https://git.fedorahosted.org/cgit/lvm2.git/tree/INSTALL++# Install Go+RUN curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz+ENV PATH /usr/local/go/bin:$PATH+ENV GOPATH /go:/go/src/github.com/docker/docker/vendor+RUN cd /usr/local/go/src && ./make.bash --no-clean 2>&1++# Compile Go for cross compilation+ENV DOCKER_CROSSPLATFORMS \+ linux/386 linux/arm \+ darwin/amd64 darwin/386 \+ freebsd/amd64 freebsd/386 freebsd/arm+# (set an explicit GOARM of 5 for maximum compatibility)+ENV GOARM 5+RUN cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done'++# Grab Go's cover tool for dead-simple code coverage testing+RUN go get golang.org/x/tools/cmd/cover++# TODO replace FPM with some very minimal debhelper stuff+RUN gem install --no-rdoc --no-ri fpm --version 1.0.2++# Get the "busybox" image source so we can build locally instead of pulling+RUN git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox++# Setup s3cmd config+RUN /bin/echo -e '[default]\naccess_key=$AWS_ACCESS_KEY\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg++# Set user.email so crosbymichael's in-container merge commits go smoothly+RUN git config --global user.email '[email protected]'++# Add an unprivileged user to be used for tests which need it+RUN groupadd -r docker+RUN useradd --create-home --gid docker unprivilegeduser++VOLUME /var/lib/docker+WORKDIR /go/src/github.com/docker/docker+ENV DOCKER_BUILDTAGS apparmor selinux++# Wrap all commands in the "docker-in-docker" script to allow nested containers+ENTRYPOINT ["hack/dind"]++# Upload docker source+COPY . /go/src/github.com/docker/dockerdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/resultnew file mode 100644index 000000000..fa558cd5e--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/docker/result@@ -0,0 +1,24 @@+(from "ubuntu:14.04")+(label "maintainer" "Tianon Gravi <[email protected]> (@tianon)" "")+(run "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -yq \tapt-utils \taufs-tools \tautomake \tbtrfs-tools \tbuild-essential \tcurl \tdpkg-sig \tgit \tiptables \tlibapparmor-dev \tlibcap-dev \tmercurial \tpandoc \tparallel \treprepro \truby1.9.1 \truby1.9.1-dev \ts3cmd=1.1.0* \t--no-install-recommends")+(run "git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103")+(run "cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper")+(run "curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz")+(env "PATH" "/usr/local/go/bin:$PATH" "")+(env "GOPATH" "/go:/go/src/github.com/docker/docker/vendor" "")+(run "cd /usr/local/go/src && ./make.bash --no-clean 2>&1")+(env "DOCKER_CROSSPLATFORMS" "linux/386 linux/arm \tdarwin/amd64 darwin/386 \tfreebsd/amd64 freebsd/386 freebsd/arm" "")+(env "GOARM" "5" "")+(run "cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done'")+(run "go get golang.org/x/tools/cmd/cover")+(run "gem install --no-rdoc --no-ri fpm --version 1.0.2")+(run "git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox")+(run "/bin/echo -e '[default]\\naccess_key=$AWS_ACCESS_KEY\\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg")+(run "git config --global user.email '[email protected]'")+(run "groupadd -r docker")+(run "useradd --create-home --gid docker unprivilegeduser")+(volume "/var/lib/docker")+(workdir "/go/src/github.com/docker/docker")+(env "DOCKER_BUILDTAGS" "apparmor selinux" "")+(entrypoint "hack/dind")+(copy "." "/go/src/github.com/docker/docker")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/Dockerfilenew file mode 100644index 000000000..08fa18ace--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/Dockerfile@@ -0,0 +1,23 @@+FROM ubuntu+ENV name value+ENV name=value+ENV name=value name2=value2+ENV name="value value1"+ENV name=value\ value2+ENV name="value'quote space'value2"+ENV name='value"double quote"value2'+ENV name=value\ value2 name2=value2\ value3+ENV name="a\"b"+ENV name="a\'b"+ENV name='a\'b'+ENV name='a\'b''+ENV name='a\"b'+ENV name="''"+# don't put anything after the next line - it must be the last line of the+# Dockerfile and it must end with \+ENV name=value \+ name1=value1 \+ name2="value2a \+ value2b" \+ name3="value3a\n\"value3b\"" \+ name4="value4a\\nvalue4b" \diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/resultnew file mode 100644index 000000000..2d56c78bd--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/env/result@@ -0,0 +1,16 @@+(from "ubuntu")+(env "name" "value" "")+(env "name" "value" "=")+(env "name" "value" "=" "name2" "value2" "=")+(env "name" "\"value value1\"" "=")+(env "name" "value\\ value2" "=")+(env "name" "\"value'quote space'value2\"" "=")+(env "name" "'value\"double quote\"value2'" "=")+(env "name" "value\\ value2" "=" "name2" "value2\\ value3" "=")+(env "name" "\"a\\\"b\"" "=")+(env "name" "\"a\\'b\"" "=")+(env "name" "'a\\'b'" "=")+(env "name" "'a\\'b''" "=")+(env "name" "'a\\\"b'" "=")+(env "name" "\"''\"" "=")+(env "name" "value" "=" "name1" "value1" "=" "name2" "\"value2a value2b\"" "=" "name3" "\"value3a\\n\\\"value3b\\\"\"" "=" "name4" "\"value4a\\\\nvalue4b\"" "=")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfilenew file mode 100644index 000000000..18e9a474f--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfile@@ -0,0 +1,9 @@+# Comment here. Should not be looking for the following parser directive.+# Hence the following line will be ignored, and the subsequent backslash+# continuation will be the default.+# escape = `++FROM image+LABEL maintainer [email protected]+ENV GOPATH \+\go\ No newline at end of filediff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfilenew file mode 100644index 000000000..bbe94a3eb--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfile@@ -0,0 +1,7 @@+# escape = `+# There is no white space line after the directives. This still succeeds, but goes+# against best practices.+FROM image+LABEL maintainer [email protected]+ENV GOPATH `+\godiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfilenew file mode 100644index 000000000..527a5c14e--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfile@@ -0,0 +1,5 @@+# syntax = docker/dockerfile+# escape = `++FROM `+ imagediff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/resultnew file mode 100644index 000000000..62e9e267d--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/result@@ -0,0 +1 @@+(from "image")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfilenew file mode 100644index 000000000..a515af152--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfile@@ -0,0 +1,6 @@+#escape = `++FROM image+LABEL maintainer [email protected]+ENV GOPATH `+\go\ No newline at end of filediff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escape/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfilenew file mode 100644index 000000000..03062394a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfile@@ -0,0 +1,14 @@+FROM ubuntu:14.04+LABEL maintainer Erik \\Hollensbe <[email protected]>\"++RUN apt-get \update && \+ apt-get \"install znc -y+ADD \conf\\" /.znc++RUN foo \++bar \++baz++CMD [ "\/usr\\\"/bin/znc", "-f", "-r" ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/resultnew file mode 100644index 000000000..29579f439--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/escapes/result@@ -0,0 +1,6 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik \\\\Hollensbe <[email protected]>\\\"" "")+(run "apt-get \\update && apt-get \\\"install znc -y")+(add "\\conf\\\\\"" "/.znc")+(run "foo bar baz")+(cmd "/usr\\\"/bin/znc" "-f" "-r")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfilenew file mode 100644index 000000000..2418e0f06--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfile@@ -0,0 +1,10 @@+FROM scratch+COPY foo /tmp/+COPY --user=me foo /tmp/+COPY --doit=true foo /tmp/+COPY --user=me --doit=true foo /tmp/+COPY --doit=true -- foo /tmp/+COPY -- foo /tmp/+CMD --doit [ "a", "b" ]+CMD --doit=true -- [ "a", "b" ]+CMD --doit -- [ ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/resultnew file mode 100644index 000000000..4578f4cba--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/flags/result@@ -0,0 +1,10 @@+(from "scratch")+(copy "foo" "/tmp/")+(copy ["--user=me"] "foo" "/tmp/")+(copy ["--doit=true"] "foo" "/tmp/")+(copy ["--user=me" "--doit=true"] "foo" "/tmp/")+(copy ["--doit=true"] "foo" "/tmp/")+(copy "foo" "/tmp/")+(cmd ["--doit"] "a" "b")+(cmd ["--doit=true"] "a" "b")+(cmd ["--doit"])diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/Dockerfilenew file mode 100644index 000000000..0e6f97e73--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/Dockerfile@@ -0,0 +1,11 @@+FROM debian+ADD check.sh main.sh /app/+CMD /app/main.sh+HEALTHCHECK+HEALTHCHECK --interval=5s --timeout=3s --retries=3 \+ CMD /app/check.sh --quiet+HEALTHCHECK CMD+HEALTHCHECK CMD a b+HEALTHCHECK --timeout=3s CMD ["foo"]+HEALTHCHECK CONNECT TCP 7000+HEALTHCHECK --start-period=0s --start-interval=0s --interval=5s --timeout=0s --retries=0 CMD ["foo"]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/resultnew file mode 100644index 000000000..dc2c8a508--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/health/result@@ -0,0 +1,10 @@+(from "debian")+(add "check.sh" "main.sh" "/app/")+(cmd "/app/main.sh")+(healthcheck)+(healthcheck ["--interval=5s" "--timeout=3s" "--retries=3"] "CMD" "/app/check.sh --quiet")+(healthcheck "CMD")+(healthcheck "CMD" "a b")+(healthcheck ["--timeout=3s"] "CMD" "foo")+(healthcheck "CONNECT" "TCP 7000")+(healthcheck ["--start-period=0s" "--start-interval=0s" "--interval=5s" "--timeout=0s" "--retries=0"] "CMD" "foo")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfilenew file mode 100644index 000000000..587fb9b54--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfile@@ -0,0 +1,15 @@+FROM ubuntu:14.04++RUN apt-get update && apt-get install wget -y+RUN wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb+RUN dpkg -i influxdb_latest_amd64.deb+RUN rm -r /opt/influxdb/shared++VOLUME /opt/influxdb/shared++CMD /usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml++EXPOSE 8083+EXPOSE 8086+EXPOSE 8090+EXPOSE 8099diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/resultnew file mode 100644index 000000000..0998e87e6--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/influxdb/result@@ -0,0 +1,11 @@+(from "ubuntu:14.04")+(run "apt-get update && apt-get install wget -y")+(run "wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb")+(run "dpkg -i influxdb_latest_amd64.deb")+(run "rm -r /opt/influxdb/shared")+(volume "/opt/influxdb/shared")+(cmd "/usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml")+(expose "8083")+(expose "8086")+(expose "8090")+(expose "8099")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfilenew file mode 100644index 000000000..39fe27d99--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfile@@ -0,0 +1 @@+CMD "[\"echo\", \"Phew, I just managed to escaped those double quotes\"]"diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/resultnew file mode 100644index 000000000..afc220c2a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/result@@ -0,0 +1 @@+(cmd "\"[\\\"echo\\\", \\\"Phew, I just managed to escaped those double quotes\\\"]\"")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfilenew file mode 100644index 000000000..eaae081a0--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfile@@ -0,0 +1 @@+CMD '["echo", "Well, JSON in a string is JSON too?"]'diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/resultnew file mode 100644index 000000000..484804e2b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/result@@ -0,0 +1 @@+(cmd "'[\"echo\", \"Well, JSON in a string is JSON too?\"]'")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfilenew file mode 100644index 000000000..c3ac63c07--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfile@@ -0,0 +1 @@+CMD ['echo','single quotes are invalid JSON']diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/resultnew file mode 100644index 000000000..614789120--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/result@@ -0,0 +1 @@+(cmd "['echo','single quotes are invalid JSON']")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfilenew file mode 100644index 000000000..5fd4afa52--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfile@@ -0,0 +1 @@+CMD ["echo", "Please, close the brackets when you're done"diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/resultnew file mode 100644index 000000000..1ffbb8ff8--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/result@@ -0,0 +1 @@+(cmd "[\"echo\", \"Please, close the brackets when you're done\"")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfilenew file mode 100644index 000000000..30cc4bb48--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfile@@ -0,0 +1 @@+CMD ["echo", "look ma, no quote!]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/resultnew file mode 100644index 000000000..32048147b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/result@@ -0,0 +1 @@+(cmd "[\"echo\", \"look ma, no quote!]")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/Dockerfilenew file mode 100644index 000000000..a58691711--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/Dockerfile@@ -0,0 +1,8 @@+CMD []+CMD [""]+CMD ["a"]+CMD ["a","b"]+CMD [ "a", "b" ]+CMD [ "a", "b" ]+CMD [ "a", "b" ]+CMD ["abc 123", "♥", "☃", "\" \\ \/ \b \f \n \r \t \u0000"]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/resultnew file mode 100644index 000000000..c6553e6e1--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/json/result@@ -0,0 +1,8 @@+(cmd)+(cmd "")+(cmd "a")+(cmd "a" "b")+(cmd "a" "b")+(cmd "a" "b")+(cmd "a" "b")+(cmd "abc 123" "♥" "☃" "\" \\ / \b \f \n \r \t \x00")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfilenew file mode 100644index 000000000..78317ace9--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04+LABEL maintainer James Turnbull "[email protected]"+ENV REFRESHED_AT 2014-06-01+RUN apt-get update+RUN apt-get --no-install-recommends install -y redis-server redis-tools+EXPOSE 6379+ENTRYPOINT [ "/usr/bin/redis-server" ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/resultnew file mode 100644index 000000000..3d175d152--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/result@@ -0,0 +1,7 @@+(from "ubuntu:14.04")+(label "maintainer" "James Turnbull \"[email protected]\"" "")+(env "REFRESHED_AT" "2014-06-01" "")+(run "apt-get update")+(run "apt-get --no-install-recommends install -y redis-server redis-tools")+(expose "6379")+(entrypoint "/usr/bin/redis-server")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfilenew file mode 100644index 000000000..27f28cb92--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfile@@ -0,0 +1,48 @@+FROM busybox:buildroot-2014.02++LABEL maintainer docker <[email protected]>++ONBUILD RUN ["echo", "test"]+ONBUILD RUN echo test+ONBUILD COPY . /+++# RUN Commands \+# linebreak in comment \+RUN ["ls", "-la"]+RUN ["echo", "'1234'"]+RUN echo "1234"+RUN echo 1234+RUN echo '1234' && \+ echo "456" && \+ echo 789+RUN sh -c 'echo root:testpass \+ > /tmp/passwd'+RUN mkdir -p /test /test2 /test3/test++# ENV \+ENV SCUBA 1 DUBA 3+ENV SCUBA "1 DUBA 3"++# CMD \+CMD ["echo", "test"]+CMD echo test+CMD echo "test"+CMD echo 'test'+CMD echo 'test' | wc -++#EXPOSE\+EXPOSE 3000+EXPOSE 9000 5000 6000++USER docker+USER docker:root++VOLUME ["/test"]+VOLUME ["/test", "/test2"]+VOLUME /test3++WORKDIR /test++ADD . /+COPY . copydiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/resultnew file mode 100644index 000000000..eee8872a6--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/result@@ -0,0 +1,29 @@+(from "busybox:buildroot-2014.02")+(label "maintainer" "docker <[email protected]>" "")+(onbuild (run "echo" "test"))+(onbuild (run "echo test"))+(onbuild (copy "." "/"))+(run "ls" "-la")+(run "echo" "'1234'")+(run "echo \"1234\"")+(run "echo 1234")+(run "echo '1234' && echo \"456\" && echo 789")+(run "sh -c 'echo root:testpass > /tmp/passwd'")+(run "mkdir -p /test /test2 /test3/test")+(env "SCUBA" "1 DUBA 3" "")+(env "SCUBA" "\"1 DUBA 3\"" "")+(cmd "echo" "test")+(cmd "echo test")+(cmd "echo \"test\"")+(cmd "echo 'test'")+(cmd "echo 'test' | wc -")+(expose "3000")+(expose "9000" "5000" "6000")+(user "docker")+(user "docker:root")+(volume "/test")+(volume "/test" "/test2")+(volume "/test3")+(workdir "/test")+(add "." "/")+(copy "." "copy")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfilenew file mode 100644index 000000000..f64c1168c--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfile@@ -0,0 +1,16 @@+FROM ubuntu:14.04++RUN apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y+ADD .muttrc /+ADD .offlineimaprc /+ADD .tmux.conf /+ADD mutt /.mutt+ADD vim /.vim+ADD vimrc /.vimrc+ADD crontab /etc/crontab+RUN chmod 644 /etc/crontab+RUN mkdir /Mail+RUN mkdir /.offlineimap+RUN echo "export TERM=screen-256color" >/.zshenv++CMD setsid cron; tmux -2diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/resultnew file mode 100644index 000000000..a0efcf04b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mail/result@@ -0,0 +1,14 @@+(from "ubuntu:14.04")+(run "apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y")+(add ".muttrc" "/")+(add ".offlineimaprc" "/")+(add ".tmux.conf" "/")+(add "mutt" "/.mutt")+(add "vim" "/.vim")+(add "vimrc" "/.vimrc")+(add "crontab" "/etc/crontab")+(run "chmod 644 /etc/crontab")+(run "mkdir /Mail")+(run "mkdir /.offlineimap")+(run "echo \"export TERM=screen-256color\" >/.zshenv")+(cmd "setsid cron; tmux -2")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfilenew file mode 100644index 000000000..57bb5976a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfile@@ -0,0 +1,3 @@+FROM foo++VOLUME /opt/nagios/var /opt/nagios/etc /opt/nagios/libexec /var/log/apache2 /usr/share/snmp/mibsdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/resultnew file mode 100644index 000000000..18dbdeeaa--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/result@@ -0,0 +1,2 @@+(from "foo")+(volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfilenew file mode 100644index 000000000..5b9ec06a6--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04++RUN apt-get update && apt-get install libcap2-bin mumble-server -y++ADD ./mumble-server.ini /etc/mumble-server.ini++CMD /usr/sbin/murmurddiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/resultnew file mode 100644index 000000000..a0036a943--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/mumble/result@@ -0,0 +1,4 @@+(from "ubuntu:14.04")+(run "apt-get update && apt-get install libcap2-bin mumble-server -y")+(add "./mumble-server.ini" "/etc/mumble-server.ini")+(cmd "/usr/sbin/murmurd")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfilenew file mode 100644index 000000000..0a35e2c6b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfile@@ -0,0 +1,14 @@+FROM ubuntu:14.04+LABEL maintainer Erik Hollensbe <[email protected]>++RUN apt-get update && apt-get install nginx-full -y+RUN rm -rf /etc/nginx+ADD etc /etc/nginx+RUN chown -R root:root /etc/nginx+RUN /usr/sbin/nginx -qt+RUN mkdir /www++CMD ["/usr/sbin/nginx"]++VOLUME /www+EXPOSE 80diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/resultnew file mode 100644index 000000000..8382e6349--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/nginx/result@@ -0,0 +1,11 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik Hollensbe <[email protected]>" "")+(run "apt-get update && apt-get install nginx-full -y")+(run "rm -rf /etc/nginx")+(add "etc" "/etc/nginx")+(run "chown -R root:root /etc/nginx")+(run "/usr/sbin/nginx -qt")+(run "mkdir /www")+(cmd "/usr/sbin/nginx")+(volume "/www")+(expose "80")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfilenew file mode 100644index 000000000..72b79bdd7--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfile@@ -0,0 +1,23 @@+FROM ubuntu:12.04++EXPOSE 27015+EXPOSE 27005+EXPOSE 26901+EXPOSE 27020++RUN apt-get update && apt-get install libc6-dev-i386 curl unzip -y+RUN mkdir -p /steam+RUN curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam+ADD ./script /steam/script+RUN /steam/steamcmd.sh +runscript /steam/script+RUN curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf+RUN curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf+ADD ./server.cfg /steam/tf2/tf/cfg/server.cfg+ADD ./ctf_2fort.cfg /steam/tf2/tf/cfg/ctf_2fort.cfg+ADD ./sourcemod.cfg /steam/tf2/tf/cfg/sourcemod/sourcemod.cfg+RUN rm -r /steam/tf2/tf/addons/sourcemod/configs+ADD ./configs /steam/tf2/tf/addons/sourcemod/configs+RUN mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en+RUN cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en++CMD cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode filldiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/resultnew file mode 100644index 000000000..d4f94cd8b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/tf2/result@@ -0,0 +1,20 @@+(from "ubuntu:12.04")+(expose "27015")+(expose "27005")+(expose "26901")+(expose "27020")+(run "apt-get update && apt-get install libc6-dev-i386 curl unzip -y")+(run "mkdir -p /steam")+(run "curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam")+(add "./script" "/steam/script")+(run "/steam/steamcmd.sh +runscript /steam/script")+(run "curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf")+(run "curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf")+(add "./server.cfg" "/steam/tf2/tf/cfg/server.cfg")+(add "./ctf_2fort.cfg" "/steam/tf2/tf/cfg/ctf_2fort.cfg")+(add "./sourcemod.cfg" "/steam/tf2/tf/cfg/sourcemod/sourcemod.cfg")+(run "rm -r /steam/tf2/tf/addons/sourcemod/configs")+(add "./configs" "/steam/tf2/tf/addons/sourcemod/configs")+(run "mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en")+(run "cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en")+(cmd "cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode fill")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfilenew file mode 100644index 000000000..90c651006--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfile@@ -0,0 +1,17 @@+# https://github.com/docker/for-win/issues/5254++FROM hello-world++ENV A path+ENV B another\\path+ENV C trailing\\backslash\\+ENV D This should not be appended to C+ENV E hello\+\+world+ENV F hello\+ \+world+ENV G hello \+\+worlddiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/resultnew file mode 100644index 000000000..23a235c2c--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/result@@ -0,0 +1,8 @@+(from "hello-world")+(env "A" "path" "")+(env "B" "another\\\\path" "")+(env "C" "trailing\\\\backslash\\\\" "")+(env "D" "This should not be appended to C" "")+(env "E" "helloworld" "")+(env "F" "hello world" "")+(env "G" "hello world" "")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfilenew file mode 100644index 000000000..484208816--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfile@@ -0,0 +1,9 @@+FROM ubuntu:14.04++RUN apt-get update -qy && apt-get install tmux zsh weechat-curses -y++ADD .weechat /.weechat+ADD .tmux.conf /+RUN echo "export TERM=screen-256color" >/.zshenv++CMD zsh -c weechatdiff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/resultnew file mode 100644index 000000000..c3abb4c54--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/weechat/result@@ -0,0 +1,6 @@+(from "ubuntu:14.04")+(run "apt-get update -qy && apt-get install tmux zsh weechat-curses -y")+(add ".weechat" "/.weechat")+(add ".tmux.conf" "/")+(run "echo \"export TERM=screen-256color\" >/.zshenv")+(cmd "zsh -c weechat")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfile b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfilenew file mode 100644index 000000000..626b126d8--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04+LABEL maintainer Erik Hollensbe <[email protected]>++RUN apt-get update && apt-get install znc -y+ADD conf /.znc++CMD [ "/usr/bin/znc", "-f", "-r" ]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/result b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/resultnew file mode 100644index 000000000..13a9827b2--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/parser/testfiles/znc/result@@ -0,0 +1,5 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik Hollensbe <[email protected]>" "")+(run "apt-get update && apt-get install znc -y")+(add "conf" "/.znc")+(cmd "/usr/bin/znc" "-f" "-r")diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.env.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.env.jsonnew file mode 100644index 000000000..1e9afc3aa--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.env.json@@ -0,0 +1,950 @@+[+ {+ "input": "hello",+ "word": "hello"+ },+ {+ "input": "he'll'o",+ "word": "hello"+ },+ {+ "input": "he'llo",+ "word": null,+ "error": true+ },+ {+ "input": "he\\'llo",+ "word": "he'llo"+ },+ {+ "input": "he\\\\'llo",+ "word": null,+ "error": true+ },+ {+ "input": "abc\\tdef",+ "word": "abctdef"+ },+ {+ "input": "\"abc\\tdef\"",+ "word": "abc\\tdef"+ },+ {+ "input": "\"abc\\\\tdef\"",+ "word": "abc\\tdef"+ },+ {+ "input": "'abc\\tdef'",+ "word": "abc\\tdef"+ },+ {+ "input": "hello\\",+ "word": "hello"+ },+ {+ "input": "hello\\\\",+ "word": "hello\\"+ },+ {+ "input": "\"hello",+ "word": null,+ "error": true+ },+ {+ "input": "\"hello\\\"",+ "word": null,+ "error": true+ },+ {+ "input": "\"hel'lo\"",+ "word": "hel'lo"+ },+ {+ "input": "'hello",+ "word": null,+ "error": true+ },+ {+ "input": "'hello\\'",+ "word": "hello\\"+ },+ {+ "input": "'hello\\there'",+ "word": "hello\\there"+ },+ {+ "input": "'hello\\\\there'",+ "word": "hello\\\\there"+ },+ {+ "input": "\"''\"",+ "word": "''"+ },+ {+ "input": "$.",+ "word": "$."+ },+ {+ "input": "he$1x",+ "word": "hex"+ },+ {+ "input": "he$.x",+ "word": "he$.x"+ },+ {+ "input": "he$pwd.",+ "word": "he."+ },+ {+ "input": "he$PWD",+ "word": "he/home"+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD"+ },+ {+ "input": "he\\\\$PWD",+ "word": "he\\/home"+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD"+ },+ {+ "input": "\"he\\\\$PWD\"",+ "word": "he\\/home"+ },+ {+ "input": "\\${}",+ "word": "${}"+ },+ {+ "input": "\\${}aaa",+ "word": "${}aaa"+ },+ {+ "input": "he\\${}",+ "word": "he${}"+ },+ {+ "input": "he\\${}xx",+ "word": "he${}xx"+ },+ {+ "input": "${}",+ "word": null,+ "error": true+ },+ {+ "input": "${}aaa",+ "word": null,+ "error": true+ },+ {+ "input": "he${}",+ "word": null,+ "error": true+ },+ {+ "input": "he${}xx",+ "word": null,+ "error": true+ },+ {+ "input": "he${hi}",+ "word": "he"+ },+ {+ "input": "he${hi}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD}",+ "word": "he/home"+ },+ {+ "input": "he${.}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:-000}xx",+ "word": "he000xx"+ },+ {+ "input": "he${PWD:-000}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-$PWD}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-${PWD:-yyy}}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-${YYY:-yyy}}xx",+ "word": "heyyyxx"+ },+ {+ "input": "he${XXX:YYY}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD?}",+ "word": "he/home"+ },+ {+ "input": "he${PWD:?}",+ "word": "he/home"+ },+ {+ "input": "he${NULL?}",+ "word": "he"+ },+ {+ "input": "he${NULL:?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:+${PWD}}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+${XXX}}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+${SHELL}}xx",+ "word": "hebashxx"+ },+ {+ "input": "he${XXX:+000}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+000}xx",+ "word": "he000xx"+ },+ {+ "input": "'he${XX}'",+ "word": "he${XX}"+ },+ {+ "input": "\"he${PWD}\"",+ "word": "he/home"+ },+ {+ "input": "\"he'$PWD'\"",+ "word": "he'/home'"+ },+ {+ "input": "\"$PWD\"",+ "word": "/home"+ },+ {+ "input": "'$PWD'",+ "word": "$PWD"+ },+ {+ "input": "'\\$PWD'",+ "word": "\\$PWD"+ },+ {+ "input": "'\"hello\"'",+ "word": "\"hello\""+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD"+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD"+ },+ {+ "input": "'he\\$PWD'",+ "word": "he\\$PWD"+ },+ {+ "input": "he${PWD",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD:=000}xx",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD:+${PWD}:}xx",+ "word": "he/home:xx"+ },+ {+ "input": "he${XXX:-\\$PWD:}xx",+ "word": "he$PWD:xx"+ },+ {+ "input": "he${XXX:-\\${PWD}z}xx",+ "word": "he${PWDz}xx"+ },+ {+ "input": "안녕하세요",+ "word": "안녕하세요"+ },+ {+ "input": "안'녕'하세요",+ "word": "안녕하세요"+ },+ {+ "input": "안'녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕\\'하세요",+ "word": "안녕'하세요"+ },+ {+ "input": "안\\\\'녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕\\t하세요",+ "word": "안녕t하세요"+ },+ {+ "input": "\"안녕\\t하세요\"",+ "word": "안녕\\t하세요"+ },+ {+ "input": "'안녕\\t하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕하세요\\",+ "word": "안녕하세요"+ },+ {+ "input": "안녕하세요\\\\",+ "word": "안녕하세요\\"+ },+ {+ "input": "\"안녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "\"안녕하세요\\\"",+ "word": null,+ "error": true+ },+ {+ "input": "\"안녕'하세요\"",+ "word": "안녕'하세요"+ },+ {+ "input": "'안녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "'안녕하세요\\'",+ "word": "안녕하세요\\"+ },+ {+ "input": "안녕$1x",+ "word": "안녕x"+ },+ {+ "input": "안녕$.x",+ "word": "안녕$.x"+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕."+ },+ {+ "input": "안녕$PWD",+ "word": "안녕/home"+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD"+ },+ {+ "input": "안녕\\\\$PWD",+ "word": "안녕\\/home"+ },+ {+ "input": "안녕\\${}",+ "word": "안녕${}"+ },+ {+ "input": "안녕\\${}xx",+ "word": "안녕${}xx"+ },+ {+ "input": "안녕${}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${}xx",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${hi}",+ "word": "안녕"+ },+ {+ "input": "안녕${hi}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD}",+ "word": "안녕/home"+ },+ {+ "input": "안녕${.}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${XXX:-000}xx",+ "word": "안녕000xx"+ },+ {+ "input": "안녕${PWD:-000}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-$PWD}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-${PWD:-yyy}}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-${YYY:-yyy}}xx",+ "word": "안녕yyyxx"+ },+ {+ "input": "안녕${XXX:YYY}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${XXX:+${PWD}}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+${XXX}}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+${SHELL}}xx",+ "word": "안녕bashxx"+ },+ {+ "input": "안녕${XXX:+000}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+000}xx",+ "word": "안녕000xx"+ },+ {+ "input": "'안녕${XX}'",+ "word": "안녕${XX}"+ },+ {+ "input": "\"안녕${PWD}\"",+ "word": "안녕/home"+ },+ {+ "input": "\"안녕'$PWD'\"",+ "word": "안녕'/home'"+ },+ {+ "input": "'\"안녕\"'",+ "word": "\"안녕\""+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD"+ },+ {+ "input": "\"안녕\\$PWD\"",+ "word": "안녕$PWD"+ },+ {+ "input": "'안녕\\$PWD'",+ "word": "안녕\\$PWD"+ },+ {+ "input": "안녕${PWD",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${PWD:=000}xx",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${PWD:+${PWD}:}xx",+ "word": "안녕/home:xx"+ },+ {+ "input": "안녕${XXX:-\\$PWD:}xx",+ "word": "안녕$PWD:xx"+ },+ {+ "input": "안녕${XXX:-\\${PWD}z}xx",+ "word": "안녕${PWDz}xx"+ },+ {+ "input": "$KOREAN",+ "word": "한국어"+ },+ {+ "input": "안녕$KOREAN",+ "word": "안녕한국어"+ },+ {+ "input": "${{aaa}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa}}",+ "word": "}"+ },+ {+ "input": "${aaa",+ "word": null,+ "error": true+ },+ {+ "input": "${{aaa:-bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb}}",+ "word": "bbb}"+ },+ {+ "input": "${aaa:-bbb",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb}",+ "word": "bbb"+ },+ {+ "input": "${aaa:-${bbb:-ccc}}",+ "word": "ccc"+ },+ {+ "input": "${aaa:-bbb ${foo}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb {foo}",+ "word": "bbb {foo"+ },+ {+ "input": "${:}",+ "word": null,+ "error": true+ },+ {+ "input": "${:-bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "${:+bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "$1",+ "word": ""+ },+ {+ "input": "${1}",+ "word": ""+ },+ {+ "input": "${1:+bbb}",+ "word": ""+ },+ {+ "input": "${1:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$2",+ "word": ""+ },+ {+ "input": "${2}",+ "word": ""+ },+ {+ "input": "${2:+bbb}",+ "word": ""+ },+ {+ "input": "${2:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$3",+ "word": ""+ },+ {+ "input": "${3}",+ "word": ""+ },+ {+ "input": "${3:+bbb}",+ "word": ""+ },+ {+ "input": "${3:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$4",+ "word": ""+ },+ {+ "input": "${4}",+ "word": ""+ },+ {+ "input": "${4:+bbb}",+ "word": ""+ },+ {+ "input": "${4:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$5",+ "word": ""+ },+ {+ "input": "${5}",+ "word": ""+ },+ {+ "input": "${5:+bbb}",+ "word": ""+ },+ {+ "input": "${5:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$6",+ "word": ""+ },+ {+ "input": "${6}",+ "word": ""+ },+ {+ "input": "${6:+bbb}",+ "word": ""+ },+ {+ "input": "${6:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$7",+ "word": ""+ },+ {+ "input": "${7}",+ "word": ""+ },+ {+ "input": "${7:+bbb}",+ "word": ""+ },+ {+ "input": "${7:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$8",+ "word": ""+ },+ {+ "input": "${8}",+ "word": ""+ },+ {+ "input": "${8:+bbb}",+ "word": ""+ },+ {+ "input": "${8:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$9",+ "word": ""+ },+ {+ "input": "${9}",+ "word": ""+ },+ {+ "input": "${9:+bbb}",+ "word": ""+ },+ {+ "input": "${9:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$999",+ "word": ""+ },+ {+ "input": "${999}",+ "word": ""+ },+ {+ "input": "${999:+bbb}",+ "word": ""+ },+ {+ "input": "${999:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$999aaa",+ "word": "aaa"+ },+ {+ "input": "${999}aaa",+ "word": "aaa"+ },+ {+ "input": "${999:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${999:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$001",+ "word": ""+ },+ {+ "input": "${001}",+ "word": ""+ },+ {+ "input": "${001:+bbb}",+ "word": ""+ },+ {+ "input": "${001:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$001aaa",+ "word": "aaa"+ },+ {+ "input": "${001}aaa",+ "word": "aaa"+ },+ {+ "input": "${001:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${001:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$@",+ "word": ""+ },+ {+ "input": "${@}",+ "word": ""+ },+ {+ "input": "${@:+bbb}",+ "word": ""+ },+ {+ "input": "${@:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$@@@",+ "word": "@@"+ },+ {+ "input": "$@aaa",+ "word": "aaa"+ },+ {+ "input": "${@}aaa",+ "word": "aaa"+ },+ {+ "input": "${@:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${@:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$*",+ "word": ""+ },+ {+ "input": "${*}",+ "word": ""+ },+ {+ "input": "${*:+bbb}",+ "word": ""+ },+ {+ "input": "${*:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$#",+ "word": ""+ },+ {+ "input": "${#}",+ "word": ""+ },+ {+ "input": "${#:+bbb}",+ "word": ""+ },+ {+ "input": "${#:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$?",+ "word": ""+ },+ {+ "input": "${?}",+ "word": ""+ },+ {+ "input": "${?:+bbb}",+ "word": ""+ },+ {+ "input": "${?:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$-",+ "word": ""+ },+ {+ "input": "${-}",+ "word": ""+ },+ {+ "input": "${-:+bbb}",+ "word": ""+ },+ {+ "input": "${-:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$$",+ "word": ""+ },+ {+ "input": "${$}",+ "word": ""+ },+ {+ "input": "${$:+bbb}",+ "word": ""+ },+ {+ "input": "${$:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$!",+ "word": ""+ },+ {+ "input": "${!}",+ "word": ""+ },+ {+ "input": "${!:+bbb}",+ "word": ""+ },+ {+ "input": "${!:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$0",+ "word": ""+ },+ {+ "input": "${0}",+ "word": ""+ },+ {+ "input": "${0:+bbb}",+ "word": ""+ },+ {+ "input": "${0:-bbb}",+ "word": "bbb"+ }+]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.jsonnew file mode 100644index 000000000..db6405333--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/envVarTest.json@@ -0,0 +1,1217 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": ["hello"]+ },+ {+ "input": "he'll'o",+ "word": "hello",+ "words": ["hello"]+ },+ {+ "input": "he'llo",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he\\'llo",+ "word": "he'llo",+ "words": ["he'llo"]+ },+ {+ "input": "he\\\\'llo",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "abc\\tdef",+ "word": "abctdef",+ "words": ["abctdef"]+ },+ {+ "input": "\"abc\\tdef\"",+ "word": "abc\\tdef",+ "words": ["abc\\tdef"]+ },+ {+ "input": "\"abc\\\\tdef\"",+ "word": "abc\\tdef",+ "words": ["abc\\tdef"]+ },+ {+ "input": "'abc\\tdef'",+ "word": "abc\\tdef",+ "words": ["abc\\tdef"]+ },+ {+ "input": "hello\\",+ "word": "hello",+ "words": ["hello"]+ },+ {+ "input": "hello\\\\",+ "word": "hello\\",+ "words": ["hello\\"]+ },+ {+ "input": "\"hello",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"hello\\\"",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"hel'lo\"",+ "word": "hel'lo",+ "words": ["hel'lo"]+ },+ {+ "input": "'hello",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "'hello\\'",+ "word": "hello\\",+ "words": ["hello\\"]+ },+ {+ "input": "'hello\\there'",+ "word": "hello\\there",+ "words": ["hello\\there"]+ },+ {+ "input": "'hello\\\\there'",+ "word": "hello\\\\there",+ "words": ["hello\\\\there"]+ },+ {+ "input": "\"''\"",+ "word": "''",+ "words": ["''"]+ },+ {+ "input": "$.",+ "word": "$.",+ "words": ["$."]+ },+ {+ "input": "he$1x",+ "word": "he$1x",+ "words": ["he$1x"]+ },+ {+ "input": "he$.x",+ "word": "he$.x",+ "words": ["he$.x"]+ },+ {+ "input": "he$pwd.",+ "word": "he$pwd.",+ "words": ["he$pwd."]+ },+ {+ "input": "he$pwd.",+ "word": "he$pwd.",+ "words": ["he$pwd."]+ },+ {+ "input": "he$PWD",+ "word": "he$PWD",+ "words": ["he$PWD"]+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD",+ "words": ["he$PWD"]+ },+ {+ "input": "he\\\\$PWD",+ "word": "he\\$PWD",+ "words": ["he\\$PWD"]+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD",+ "words": ["he$PWD"]+ },+ {+ "input": "\"he\\\\$PWD\"",+ "word": "he\\$PWD",+ "words": ["he\\$PWD"]+ },+ {+ "input": "\\${}",+ "word": "${}",+ "words": ["${}"]+ },+ {+ "input": "\\${}aaa",+ "word": "${}aaa",+ "words": ["${}aaa"]+ },+ {+ "input": "he\\${}",+ "word": "he${}",+ "words": ["he${}"]+ },+ {+ "input": "he\\${}xx",+ "word": "he${}xx",+ "words": ["he${}xx"]+ },+ {+ "input": "${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${}aaa",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${}xx",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${hi}",+ "word": "he${hi}",+ "words": ["he${hi}"]+ },+ {+ "input": "he${hi}xx",+ "word": "he${hi}xx",+ "words": ["he${hi}xx"]+ },+ {+ "input": "he${PWD}",+ "word": "he${PWD}",+ "words": ["he${PWD}"]+ },+ {+ "input": "he${.}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${XXX:-000}xx",+ "word": "he${XXX:-000}xx",+ "words": ["he${XXX:-000}xx"],+ "buildkitWords": ["${XXX:-000}xx"]+ },+ {+ "input": "he${PWD:-000}xx",+ "word": "he${PWD:-000}xx",+ "words": ["he${PWD:-000}xx"],+ "buildkitWords": ["${PWD:-000}xx"]+ },+ {+ "input": "he${XXX:-$PWD}xx",+ "word": "he${XXX:-$PWD}xx",+ "words": ["he${XXX:-$PWD}xx"],+ "buildkitWords": ["${XXX:-$PWD}xx"]+ },+ {+ "input": "he${XXX:-${PWD:-yyy}}xx",+ "word": "he${XXX:-${PWD:-yyy}}xx",+ "words": ["he${XXX:-${PWD:-yyy}}xx"],+ "buildkitWords": ["${XXX:-${PWD:-yyy}}xx"]+ },+ {+ "input": "he${XXX:-${YYY:-yyy}}xx",+ "word": "he${XXX:-${YYY:-yyy}}xx",+ "words": ["he${XXX:-${YYY:-yyy}}xx"],+ "buildkitWords": ["${XXX:-${YYY:-yyy}}xx"]+ },+ {+ "input": "he${XXX:YYY}",+ "word": "he${XXX:YYY}",+ "words": ["he${XXX:YYY}"],+ "buildkitWords": ["${XXX:YYY}"]+ },+ {+ "input": "he${XXX?}",+ "word": "he${XXX?}",+ "words": ["he${XXX?}"],+ "buildkitWords": ["${XXX?}"]+ },+ {+ "input": "he${XXX:?}",+ "word": "he${XXX:?}",+ "words": ["he${XXX:?}"],+ "buildkitWords": ["${XXX:?}"]+ },+ {+ "input": "he${PWD?}",+ "word": "he${PWD?}",+ "words": ["he${PWD?}"],+ "buildkitWords": ["${PWD?}"]+ },+ {+ "input": "he${PWD:?}",+ "word": "he${PWD:?}",+ "words": ["he${PWD:?}"],+ "buildkitWords": ["${PWD:?}"]+ },+ {+ "input": "he${NULL?}",+ "word": "he${NULL?}",+ "words": ["he${NULL?}"],+ "buildkitWords": ["${NULL?}"]+ },+ {+ "input": "he${NULL:?}",+ "word": "he${NULL:?}",+ "words": ["he${NULL:?}"],+ "buildkitWords": ["${NULL:?}"]+ },+ {+ "input": "he${XXX:+${PWD}}xx",+ "word": "he${XXX:+${PWD}}xx",+ "words": ["he${XXX:+${PWD}}xx"],+ "buildkitWords": ["${XXX:+${PWD}}xx"]+ },+ {+ "input": "he${PWD:+${XXX}}xx",+ "word": "he${PWD:+${XXX}}xx",+ "words": ["he${PWD:+${XXX}}xx"],+ "buildkitWords": ["${PWD:+${XXX}}xx"]+ },+ {+ "input": "he${PWD:+${SHELL}}xx",+ "word": "he${PWD:+${SHELL}}xx",+ "words": ["he${PWD:+${SHELL}}xx"],+ "buildkitWords": ["${PWD:+${SHELL}}xx"]+ },+ {+ "input": "he${XXX:+000}xx",+ "word": "he${XXX:+000}xx",+ "words": ["he${XXX:+000}xx"],+ "buildkitWords": ["${XXX:+000}xx"]+ },+ {+ "input": "he${PWD:+000}xx",+ "word": "he${PWD:+000}xx",+ "words": ["he${PWD:+000}xx"],+ "buildkitWords": ["${PWD:+000}xx"]+ },+ {+ "input": "'he${XX}'",+ "word": "he${XX}",+ "words": ["he${XX}"]+ },+ {+ "input": "\"he${PWD}\"",+ "word": "he${PWD}",+ "words": ["he${PWD}"]+ },+ {+ "input": "\"he'$PWD'\"",+ "word": "he'$PWD'",+ "words": ["he'$PWD'"]+ },+ {+ "input": "\"$PWD\"",+ "word": "$PWD",+ "words": ["$PWD"]+ },+ {+ "input": "'$PWD'",+ "word": "$PWD",+ "words": ["$PWD"]+ },+ {+ "input": "'\\$PWD'",+ "word": "\\$PWD",+ "words": ["\\$PWD"]+ },+ {+ "input": "'\"hello\"'",+ "word": "\"hello\"",+ "words": ["\"hello\""]+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD",+ "words": ["he$PWD"]+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD",+ "words": ["he$PWD"]+ },+ {+ "input": "'he\\$PWD'",+ "word": "he\\$PWD",+ "words": ["he\\$PWD"]+ },+ {+ "input": "he${PWD",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${PWD:=000}xx",+ "word": "he${PWD:=000}xx",+ "words": ["he${PWD:=000}xx"],+ "buildkitWords": ["${PWD:=000}xx"]+ },+ {+ "input": "he${PWD:+${PWD}:}xx",+ "word": "he${PWD:+${PWD}:}xx",+ "words": ["he${PWD:+${PWD}:}xx"],+ "buildkitWords": ["${PWD:+${PWD}:}xx"]+ },+ {+ "input": "he${XXX:-\\$PWD:}xx",+ "word": "he${XXX:-$PWD:}xx",+ "words": ["he${XXX:-$PWD:}xx"],+ "buildkitWords": ["${XXX:-$PWD:}xx"]+ },+ {+ "input": "he${XXX:-\\${PWD}z}xx",+ "word": "he${XXX:-${PWD}z}xx",+ "words": ["he${XXX:-${PWD}z}xx"],+ "buildkitWords": ["${XXX:-${PWD}z}xx"]+ },+ {+ "input": "안녕하세요",+ "word": "안녕하세요",+ "words": ["안녕하세요"]+ },+ {+ "input": "안'녕'하세요",+ "word": "안녕하세요",+ "words": ["안녕하세요"]+ },+ {+ "input": "안'녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕\\'하세요",+ "word": "안녕'하세요",+ "words": ["안녕'하세요"]+ },+ {+ "input": "안\\\\'녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕\\t하세요",+ "word": "안녕t하세요",+ "words": ["안녕t하세요"]+ },+ {+ "input": "\"안녕\\t하세요\"",+ "word": "안녕\\t하세요",+ "words": ["안녕\\t하세요"]+ },+ {+ "input": "'안녕\\t하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕하세요\\",+ "word": "안녕하세요",+ "words": ["안녕하세요"]+ },+ {+ "input": "안녕하세요\\\\",+ "word": "안녕하세요\\",+ "words": ["안녕하세요\\"]+ },+ {+ "input": "\"안녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"안녕하세요\\\"",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"안녕'하세요\"",+ "word": "안녕'하세요",+ "words": ["안녕'하세요"]+ },+ {+ "input": "'안녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "'안녕하세요\\'",+ "word": "안녕하세요\\",+ "words": ["안녕하세요\\"]+ },+ {+ "input": "안녕$1x",+ "word": "안녕$1x",+ "words": ["안녕$1x"]+ },+ {+ "input": "안녕$.x",+ "word": "안녕$.x",+ "words": ["안녕$.x"]+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕$pwd.",+ "words": ["안녕$pwd."]+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕$pwd.",+ "words": ["안녕$pwd."]+ },+ {+ "input": "안녕$PWD",+ "word": "안녕$PWD",+ "words": ["안녕$PWD"]+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD",+ "words": ["안녕$PWD"]+ },+ {+ "input": "안녕\\\\$PWD",+ "word": "안녕\\$PWD",+ "words": ["안녕\\$PWD"]+ },+ {+ "input": "안녕\\${}",+ "word": "안녕${}",+ "words": ["안녕${}"]+ },+ {+ "input": "안녕\\${}xx",+ "word": "안녕${}xx",+ "words": ["안녕${}xx"]+ },+ {+ "input": "안녕${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${}xx",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${hi}",+ "word": "안녕${hi}",+ "words": ["안녕${hi}"]+ },+ {+ "input": "안녕${hi}xx",+ "word": "안녕${hi}xx",+ "words": ["안녕${hi}xx"]+ },+ {+ "input": "안녕${PWD}",+ "word": "안녕${PWD}",+ "words": ["안녕${PWD}"]+ },+ {+ "input": "안녕${.}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${XXX:-000}xx",+ "word": "안녕${XXX:-000}xx",+ "words": ["안녕${XXX:-000}xx"],+ "buildkitWords": ["${XXX:-000}xx"]+ },+ {+ "input": "안녕${PWD:-000}xx",+ "word": "안녕${PWD:-000}xx",+ "words": ["안녕${PWD:-000}xx"],+ "buildkitWords": ["${PWD:-000}xx"]+ },+ {+ "input": "안녕${XXX:-$PWD}xx",+ "word": "안녕${XXX:-$PWD}xx",+ "words": ["안녕${XXX:-$PWD}xx"],+ "buildkitWords": ["${XXX:-$PWD}xx"]+ },+ {+ "input": "안녕${XXX:-${PWD:-yyy}}xx",+ "word": "안녕${XXX:-${PWD:-yyy}}xx",+ "words": ["안녕${XXX:-${PWD:-yyy}}xx"],+ "buildkitWords": ["${XXX:-${PWD:-yyy}}xx"]+ },+ {+ "input": "안녕${XXX:-${YYY:-yyy}}xx",+ "word": "안녕${XXX:-${YYY:-yyy}}xx",+ "words": ["안녕${XXX:-${YYY:-yyy}}xx"],+ "buildkitWords": ["${XXX:-${YYY:-yyy}}xx"]+ },+ {+ "input": "안녕${XXX:YYY}",+ "word": "안녕${XXX:YYY}",+ "words": ["안녕${XXX:YYY}"],+ "buildkitWords": ["${XXX:YYY}"]+ },+ {+ "input": "안녕${XXX:+${PWD}}xx",+ "word": "안녕${XXX:+${PWD}}xx",+ "words": ["안녕${XXX:+${PWD}}xx"],+ "buildkitWords": ["${XXX:+${PWD}}xx"]+ },+ {+ "input": "안녕${PWD:+${XXX}}xx",+ "word": "안녕${PWD:+${XXX}}xx",+ "words": ["안녕${PWD:+${XXX}}xx"],+ "buildkitWords": ["${PWD:+${XXX}}xx"]+ },+ {+ "input": "안녕${PWD:+${SHELL}}xx",+ "word": "안녕${PWD:+${SHELL}}xx",+ "words": ["안녕${PWD:+${SHELL}}xx"],+ "buildkitWords": ["${PWD:+${SHELL}}xx"]+ },+ {+ "input": "안녕${XXX:+000}xx",+ "word": "안녕${XXX:+000}xx",+ "words": ["안녕${XXX:+000}xx"],+ "buildkitWords": ["${XXX:+000}xx"]+ },+ {+ "input": "안녕${PWD:+000}xx",+ "word": "안녕${PWD:+000}xx",+ "words": ["안녕${PWD:+000}xx"],+ "buildkitWords": ["${PWD:+000}xx"]+ },+ {+ "input": "'안녕${XX}'",+ "word": "안녕${XX}",+ "words": ["안녕${XX}"]+ },+ {+ "input": "\"안녕${PWD}\"",+ "word": "안녕${PWD}",+ "words": ["안녕${PWD}"]+ },+ {+ "input": "\"안녕'$PWD'\"",+ "word": "안녕'$PWD'",+ "words": ["안녕'$PWD'"]+ },+ {+ "input": "'\"안녕\"'",+ "word": "\"안녕\"",+ "words": ["\"안녕\""]+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD",+ "words": ["안녕$PWD"]+ },+ {+ "input": "\"안녕\\$PWD\"",+ "word": "안녕$PWD",+ "words": ["안녕$PWD"]+ },+ {+ "input": "'안녕\\$PWD'",+ "word": "안녕\\$PWD",+ "words": ["안녕\\$PWD"]+ },+ {+ "input": "안녕${PWD",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${PWD:=000}xx",+ "word": "안녕${PWD:=000}xx",+ "words": ["안녕${PWD:=000}xx"],+ "buildkitWords": ["${PWD:=000}xx"]+ },+ {+ "input": "안녕${PWD:+${PWD}:}xx",+ "word": "안녕${PWD:+${PWD}:}xx",+ "words": ["안녕${PWD:+${PWD}:}xx"],+ "buildkitWords": ["${PWD:+${PWD}:}xx"]+ },+ {+ "input": "안녕${XXX:-\\$PWD:}xx",+ "word": "안녕${XXX:-$PWD:}xx",+ "words": ["안녕${XXX:-$PWD:}xx"],+ "buildkitWords": ["${XXX:-$PWD:}xx"]+ },+ {+ "input": "안녕${XXX:-\\${PWD}z}xx",+ "word": "안녕${XXX:-${PWD}z}xx",+ "words": ["안녕${XXX:-${PWD}z}xx"],+ "buildkitWords": ["${XXX:-${PWD}z}xx"]+ },+ {+ "input": "$KOREAN",+ "word": "$KOREAN",+ "words": ["$KOREAN"]+ },+ {+ "input": "안녕$KOREAN",+ "word": "안녕$KOREAN",+ "words": ["안녕$KOREAN"]+ },+ {+ "input": "${{aaa}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa}}",+ "word": "${aaa}}",+ "words": ["${aaa}}"]+ },+ {+ "input": "${aaa",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${{aaa:-bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb}}",+ "word": "${aaa:-bbb}}",+ "words": ["${aaa:-bbb}}"]+ },+ {+ "input": "${aaa:-bbb",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb}",+ "word": "${aaa:-bbb}",+ "words": ["${aaa:-bbb}"]+ },+ {+ "input": "${aaa:-${bbb:-ccc}}",+ "word": "${aaa:-${bbb:-ccc}}",+ "words": ["${aaa:-${bbb:-ccc}}"]+ },+ {+ "input": "${aaa:-bbb ${foo}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb {foo}",+ "word": "${aaa:-bbb {foo}",+ "words": ["${aaa:-bbb", "{foo}"]+ },+ {+ "input": "${:}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${:-bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${:+bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "$1",+ "word": "$1",+ "words": ["$1"]+ },+ {+ "input": "${1}",+ "word": "${1}",+ "words": ["${1}"]+ },+ {+ "input": "${1:+bbb}",+ "word": "${1:+bbb}",+ "words": ["${1:+bbb}"]+ },+ {+ "input": "${1:-bbb}",+ "word": "${1:-bbb}",+ "words": ["${1:-bbb}"]+ },+ {+ "input": "$2",+ "word": "$2",+ "words": ["$2"]+ },+ {+ "input": "${2}",+ "word": "${2}",+ "words": ["${2}"]+ },+ {+ "input": "${2:+bbb}",+ "word": "${2:+bbb}",+ "words": ["${2:+bbb}"]+ },+ {+ "input": "${2:-bbb}",+ "word": "${2:-bbb}",+ "words": ["${2:-bbb}"]+ },+ {+ "input": "$3",+ "word": "$3",+ "words": ["$3"]+ },+ {+ "input": "${3}",+ "word": "${3}",+ "words": ["${3}"]+ },+ {+ "input": "${3:+bbb}",+ "word": "${3:+bbb}",+ "words": ["${3:+bbb}"]+ },+ {+ "input": "${3:-bbb}",+ "word": "${3:-bbb}",+ "words": ["${3:-bbb}"]+ },+ {+ "input": "$4",+ "word": "$4",+ "words": ["$4"]+ },+ {+ "input": "${4}",+ "word": "${4}",+ "words": ["${4}"]+ },+ {+ "input": "${4:+bbb}",+ "word": "${4:+bbb}",+ "words": ["${4:+bbb}"]+ },+ {+ "input": "${4:-bbb}",+ "word": "${4:-bbb}",+ "words": ["${4:-bbb}"]+ },+ {+ "input": "$5",+ "word": "$5",+ "words": ["$5"]+ },+ {+ "input": "${5}",+ "word": "${5}",+ "words": ["${5}"]+ },+ {+ "input": "${5:+bbb}",+ "word": "${5:+bbb}",+ "words": ["${5:+bbb}"]+ },+ {+ "input": "${5:-bbb}",+ "word": "${5:-bbb}",+ "words": ["${5:-bbb}"]+ },+ {+ "input": "$6",+ "word": "$6",+ "words": ["$6"]+ },+ {+ "input": "${6}",+ "word": "${6}",+ "words": ["${6}"]+ },+ {+ "input": "${6:+bbb}",+ "word": "${6:+bbb}",+ "words": ["${6:+bbb}"]+ },+ {+ "input": "${6:-bbb}",+ "word": "${6:-bbb}",+ "words": ["${6:-bbb}"]+ },+ {+ "input": "$7",+ "word": "$7",+ "words": ["$7"]+ },+ {+ "input": "${7}",+ "word": "${7}",+ "words": ["${7}"]+ },+ {+ "input": "${7:+bbb}",+ "word": "${7:+bbb}",+ "words": ["${7:+bbb}"]+ },+ {+ "input": "${7:-bbb}",+ "word": "${7:-bbb}",+ "words": ["${7:-bbb}"]+ },+ {+ "input": "$8",+ "word": "$8",+ "words": ["$8"]+ },+ {+ "input": "${8}",+ "word": "${8}",+ "words": ["${8}"]+ },+ {+ "input": "${8:+bbb}",+ "word": "${8:+bbb}",+ "words": ["${8:+bbb}"]+ },+ {+ "input": "${8:-bbb}",+ "word": "${8:-bbb}",+ "words": ["${8:-bbb}"]+ },+ {+ "input": "$9",+ "word": "$9",+ "words": ["$9"]+ },+ {+ "input": "${9}",+ "word": "${9}",+ "words": ["${9}"]+ },+ {+ "input": "${9:+bbb}",+ "word": "${9:+bbb}",+ "words": ["${9:+bbb}"]+ },+ {+ "input": "${9:-bbb}",+ "word": "${9:-bbb}",+ "words": ["${9:-bbb}"]+ },+ {+ "input": "$999",+ "word": "$999",+ "words": ["$999"]+ },+ {+ "input": "${999}",+ "word": "${999}",+ "words": ["${999}"]+ },+ {+ "input": "${999:+bbb}",+ "word": "${999:+bbb}",+ "words": ["${999:+bbb}"]+ },+ {+ "input": "${999:-bbb}",+ "word": "${999:-bbb}",+ "words": ["${999:-bbb}"]+ },+ {+ "input": "$999aaa",+ "word": "$999aaa",+ "words": ["$999aaa"]+ },+ {+ "input": "${999}aaa",+ "word": "${999}aaa",+ "words": ["${999}aaa"]+ },+ {+ "input": "${999:+bbb}aaa",+ "word": "${999:+bbb}aaa",+ "words": ["${999:+bbb}aaa"]+ },+ {+ "input": "${999:-bbb}aaa",+ "word": "${999:-bbb}aaa",+ "words": ["${999:-bbb}aaa"]+ },+ {+ "input": "$001",+ "word": "$001",+ "words": ["$001"]+ },+ {+ "input": "${001}",+ "word": "${001}",+ "words": ["${001}"]+ },+ {+ "input": "${001:+bbb}",+ "word": "${001:+bbb}",+ "words": ["${001:+bbb}"]+ },+ {+ "input": "${001:-bbb}",+ "word": "${001:-bbb}",+ "words": ["${001:-bbb}"]+ },+ {+ "input": "$001aaa",+ "word": "$001aaa",+ "words": ["$001aaa"]+ },+ {+ "input": "${001}aaa",+ "word": "${001}aaa",+ "words": ["${001}aaa"]+ },+ {+ "input": "${001:+bbb}aaa",+ "word": "${001:+bbb}aaa",+ "words": ["${001:+bbb}aaa"]+ },+ {+ "input": "${001:-bbb}aaa",+ "word": "${001:-bbb}aaa",+ "words": ["${001:-bbb}aaa"]+ },+ {+ "input": "$@",+ "word": "$@",+ "words": ["$@"]+ },+ {+ "input": "${@}",+ "word": "${@}",+ "words": ["${@}"]+ },+ {+ "input": "${@:+bbb}",+ "word": "${@:+bbb}",+ "words": ["${@:+bbb}"]+ },+ {+ "input": "${@:-bbb}",+ "word": "${@:-bbb}",+ "words": ["${@:-bbb}"]+ },+ {+ "input": "$@@@",+ "word": "$@@@",+ "words": ["$@@@"]+ },+ {+ "input": "$@aaa",+ "word": "$@aaa",+ "words": ["$@aaa"]+ },+ {+ "input": "${@}aaa",+ "word": "${@}aaa",+ "words": ["${@}aaa"]+ },+ {+ "input": "${@:+bbb}aaa",+ "word": "${@:+bbb}aaa",+ "words": ["${@:+bbb}aaa"]+ },+ {+ "input": "${@:-bbb}aaa",+ "word": "${@:-bbb}aaa",+ "words": ["${@:-bbb}aaa"]+ },+ {+ "input": "$*",+ "word": "$*",+ "words": ["$*"]+ },+ {+ "input": "${*}",+ "word": "${*}",+ "words": ["${*}"]+ },+ {+ "input": "${*:+bbb}",+ "word": "${*:+bbb}",+ "words": ["${*:+bbb}"]+ },+ {+ "input": "${*:-bbb}",+ "word": "${*:-bbb}",+ "words": ["${*:-bbb}"]+ },+ {+ "input": "$#",+ "word": "$#",+ "words": ["$#"]+ },+ {+ "input": "${#}",+ "word": "${#}",+ "words": ["${#}"]+ },+ {+ "input": "${#:+bbb}",+ "word": "${#:+bbb}",+ "words": ["${#:+bbb}"]+ },+ {+ "input": "${#:-bbb}",+ "word": "${#:-bbb}",+ "words": ["${#:-bbb}"]+ },+ {+ "input": "$?",+ "word": "$?",+ "words": ["$?"]+ },+ {+ "input": "${?}",+ "word": "${?}",+ "words": ["${?}"]+ },+ {+ "input": "${?:+bbb}",+ "word": "${?:+bbb}",+ "words": ["${?:+bbb}"]+ },+ {+ "input": "${?:-bbb}",+ "word": "${?:-bbb}",+ "words": ["${?:-bbb}"]+ },+ {+ "input": "$-",+ "word": "$-",+ "words": ["$-"]+ },+ {+ "input": "${-}",+ "word": "${-}",+ "words": ["${-}"]+ },+ {+ "input": "${-:+bbb}",+ "word": "${-:+bbb}",+ "words": ["${-:+bbb}"]+ },+ {+ "input": "${-:-bbb}",+ "word": "${-:-bbb}",+ "words": ["${-:-bbb}"]+ },+ {+ "input": "$$",+ "word": "$$",+ "words": ["$$"]+ },+ {+ "input": "${$}",+ "word": "${$}",+ "words": ["${$}"]+ },+ {+ "input": "${$:+bbb}",+ "word": "${$:+bbb}",+ "words": ["${$:+bbb}"]+ },+ {+ "input": "${$:-bbb}",+ "word": "${$:-bbb}",+ "words": ["${$:-bbb}"]+ },+ {+ "input": "$!",+ "word": "$!",+ "words": ["$!"]+ },+ {+ "input": "${!}",+ "word": "${!}",+ "words": ["${!}"]+ },+ {+ "input": "${!:+bbb}",+ "word": "${!:+bbb}",+ "words": ["${!:+bbb}"]+ },+ {+ "input": "${!:-bbb}",+ "word": "${!:-bbb}",+ "words": ["${!:-bbb}"]+ },+ {+ "input": "$0",+ "word": "$0",+ "words": ["$0"]+ },+ {+ "input": "${0}",+ "word": "${0}",+ "words": ["${0}"]+ },+ {+ "input": "${0:+bbb}",+ "word": "${0:+bbb}",+ "words": ["${0:+bbb}"]+ },+ {+ "input": "${0:-bbb}",+ "word": "${0:-bbb}",+ "words": ["${0:-bbb}"]+ }+]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/processWithMatches.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/processWithMatches.jsonnew file mode 100644index 000000000..f8ddc5a6b--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/processWithMatches.json@@ -0,0 +1,341 @@+[+ {+ "input": "x",+ "env": {+ "DUMMY": "dummy"+ },+ "word": "x"+ },+ {+ "input": "x ${UNUSED}",+ "env": {+ "DUMMY": "dummy"+ },+ "word": "x "+ },+ {+ "input": "x ${FOO}",+ "env": {+ "FOO": "y"+ },+ "word": "x y"+ },+ {+ "input": "${FOO-aaa} ${BAR-bbb} ${BAZ-ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx ccc"+ },+ {+ "input": "${FOO:-aaa} ${BAR:-bbb} ${BAZ:-ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx bbb ccc"+ },+ {+ "input": "${FOO:-}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${FOO:-}",+ "env": {},+ "word": ""+ },+ {+ "input": "${FOO+aaa} ${BAR+bbb} ${BAZ+ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "aaa bbb "+ },+ {+ "input": "${FOO:+aaa} ${BAR:+bbb} ${BAZ:+ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "aaa "+ },+ {+ "input": "${FOO?aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${BAR?bbb}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": ""+ },+ {+ "input": "${BAZ?ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO:?aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${BAR:?bbb}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${BAZ:?ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${BAZ:?}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=:aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO#()[]{\\}^$.\\*\\?|\\\\}",+ "env": {+ "FOO": "()[]{}^$.*?|\\x"+ },+ "word": "x"+ },+ {+ "input": "${FOO%%\\**}",+ "env": {+ "FOO": "xx**"+ },+ "word": "xx"+ },+ {+ "input": "${FOO#*x*y}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "y"+ },+ {+ "input": "${FOO#*}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": "x"+ },+ "word": "xyy"+ },+ {+ "input": "${FOO#$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO##*x}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "yy"+ },+ {+ "input": "${FOO##}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#?\\?}",+ "env": {+ "FOO": "???y"+ },+ "word": "?y"+ },+ {+ "input": "${ABC:-.}${FOO%x}${ABC:-.}",+ "env": {+ "FOO": "xxyy"+ },+ "word": ".xxyy."+ },+ {+ "input": "${FOO%%\\**\\*}",+ "env": {+ "FOO": "a***yy*"+ },+ "word": "a"+ },+ {+ "input": "${FOO%}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO%%$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO:#}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:##}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:%}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:%%}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO/$NEEDLE/.} - ${FOO//$NEEDLE/.}",+ "env": {+ "FOO": "/foo*/*/*.txt",+ "NEEDLE": "\\*/"+ },+ "word": "/foo.*/*.txt - /foo..*.txt"+ },+ {+ "input": "${FOO/$NEEDLE/} - ${FOO//$NEEDLE/}",+ "env": {+ "FOO": "/tmp/tmp/bar.txt",+ "NEEDLE": "/tmp"+ },+ "word": "/tmp/bar.txt - /bar.txt"+ },+ {+ "input": "${FOO/$NEEDLE/$REPLACEMENT} - ${FOO//$NEEDLE/$REPLACEMENT}",+ "env": {+ "FOO": "/a/foo/b/c.txt",+ "NEEDLE": "/?/",+ "REPLACEMENT": "/"+ },+ "word": "/foo/b/c.txt - /foo/c.txt"+ },+ {+ "input": "${FOO/$NEEDLE/$REPLACEMENT}",+ "env": {+ "FOO": "http://google.de",+ "NEEDLE": "http://",+ "REPLACEMENT": "https://"+ },+ "word": "https://google.de"+ },+ {+ "input": "${FOO//\\//\\/}",+ "env": {+ "FOO": "/tmp/foo.txt"+ },+ "word": "\\/tmp\\/foo.txt"+ },+ {+ "input": "${FOO/$BAR/ww}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "wwxxyy"+ },+ {+ "input": "${FOO//ww}",+ "env": {+ "FOO": "xxyy"+ },+ "error": true+ },+ {+ "input": "${FOO//}",+ "env": {+ "FOO": "xxyy"+ },+ "error": true+ },+ {+ "input": "${FOO///}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO///}",+ "env": {},+ "word": ""+ }+]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.env.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.env.jsonnew file mode 100644index 000000000..2b9733a33--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.env.json@@ -0,0 +1,219 @@+[+ {+ "input": "hello",+ "env": {},+ "words": ["hello"]+ },+ {+ "input": "hello${hi}bye",+ "env": {},+ "words": ["hellobye"]+ },+ {+ "input": "hello${hi}bye",+ "env": {+ "hi": "hi"+ },+ "words": ["hellohibye"]+ },+ {+ "input": "hello${space}bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["helloabc", "defbye"]+ },+ {+ "input": "hello\"${space}\"bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["helloabc defbye"]+ },+ {+ "input": "hello \"${space}\"bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["hello", "abc defbye"]+ },+ {+ "input": "hello${leading}def",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello", "ab", "cdef"]+ },+ {+ "input": "hello\"${leading}\" def",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello ab c", "def"]+ },+ {+ "input": "hello\"${leading}\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello ab c"]+ },+ {+ "input": "hello${leading}",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello", "ab", "c"]+ },+ {+ "input": "hello${trailing}",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab", "c"]+ },+ {+ "input": "hello${trailing}d",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab", "c", "d"]+ },+ {+ "input": "hello\"${trailing}\"d",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab c d"]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab c "]+ },+ {+ "input": "hello\" there \"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello there "]+ },+ {+ "input": "hello there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello", "there"]+ },+ {+ "input": "hello\\ there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello there"]+ },+ {+ "input": "hello\" there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "error": true+ },+ {+ "input": "hello\\\" there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\"", "there"]+ },+ {+ "input": "hello\"\\\\there\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello\"\\there\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello'\\\\there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\\\there"]+ },+ {+ "input": "hello'\\there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello'$there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello$there"]+ }+]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.jsonnew file mode 100644index 000000000..daa2f3aa7--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.json@@ -0,0 +1,123 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": ["hello"]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": ["hello${hi}bye"]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": ["hello${hi}bye"]+ },+ {+ "input": "hello${space}bye",+ "word": "hello${space}bye",+ "words": ["hello${space}bye"]+ },+ {+ "input": "hello\"${space}\"bye",+ "word": "hello${space}bye",+ "words": ["hello${space}bye"]+ },+ {+ "input": "hello \"${space}\"bye",+ "word": "hello ${space}bye",+ "words": ["hello", "${space}bye"]+ },+ {+ "input": "hello${leading}def",+ "word": "hello${leading}def",+ "words": ["hello${leading}def"]+ },+ {+ "input": "hello\"${leading}\" def",+ "word": "hello${leading} def",+ "words": ["hello${leading}", "def"]+ },+ {+ "input": "hello\"${leading}\"",+ "word": "hello${leading}",+ "words": ["hello${leading}"]+ },+ {+ "input": "hello${leading}",+ "word": "hello${leading}",+ "words": ["hello${leading}"]+ },+ {+ "input": "hello${trailing}",+ "word": "hello${trailing}",+ "words": ["hello${trailing}"]+ },+ {+ "input": "hello${trailing}d",+ "word": "hello${trailing}d",+ "words": ["hello${trailing}d"]+ },+ {+ "input": "hello\"${trailing}\"d",+ "word": "hello${trailing}d",+ "words": ["hello${trailing}d"]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "word": "hello${trailing}",+ "words": ["hello${trailing}"]+ },+ {+ "input": "hello\" there \"",+ "word": "hello there ",+ "words": ["hello there "]+ },+ {+ "input": "hello there",+ "word": "hello there",+ "words": ["hello", "there"]+ },+ {+ "input": "hello\\ there",+ "word": "hello there",+ "words": ["hello there"]+ },+ {+ "input": "hello\" there",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "hello\\\" there",+ "word": "hello\" there",+ "words": ["hello\"", "there"]+ },+ {+ "input": "hello\"\\\\there\"",+ "word": "hello\\there",+ "words": ["hello\\there"]+ },+ {+ "input": "hello\"\\there\"",+ "word": "hello\\there",+ "words": ["hello\\there"]+ },+ {+ "input": "hello'\\\\there'",+ "word": "hello\\\\there",+ "words": ["hello\\\\there"]+ },+ {+ "input": "hello'\\there'",+ "word": "hello\\there",+ "words": ["hello\\there"]+ },+ {+ "input": "hello'$there'",+ "word": "hello$there",+ "words": ["hello$there"]+ }+]diff --git a/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.json b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.jsonnew file mode 100644index 000000000..1b10d9153--- /dev/null+++ b/packages/dockerfile-utils-js/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.json@@ -0,0 +1,123 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": ["hello"]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": ["hello${hi}bye"]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": ["hello${hi}bye"]+ },+ {+ "input": "hello${space}bye",+ "word": "hello${space}bye",+ "words": ["hello${space}bye"]+ },+ {+ "input": "hello\"${space}\"bye",+ "word": "hello\"${space}\"bye",+ "words": ["hello\"${space}\"bye"]+ },+ {+ "input": "hello \"${space}\"bye",+ "word": "hello \"${space}\"bye",+ "words": ["hello", "\"${space}\"bye"]+ },+ {+ "input": "hello${leading}def",+ "word": "hello${leading}def",+ "words": ["hello${leading}def"]+ },+ {+ "input": "hello\"${leading}\" def",+ "word": "hello\"${leading}\" def",+ "words": ["hello\"${leading}\"", "def"]+ },+ {+ "input": "hello\"${leading}\"",+ "word": "hello\"${leading}\"",+ "words": ["hello\"${leading}\""]+ },+ {+ "input": "hello${leading}",+ "word": "hello${leading}",+ "words": ["hello${leading}"]+ },+ {+ "input": "hello${trailing}",+ "word": "hello${trailing}",+ "words": ["hello${trailing}"]+ },+ {+ "input": "hello${trailing}d",+ "word": "hello${trailing}d",+ "words": ["hello${trailing}d"]+ },+ {+ "input": "hello\"${trailing}\"d",+ "word": "hello\"${trailing}\"d",+ "words": ["hello\"${trailing}\"d"]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "word": "hel\"lo${trailing}\"",+ "words": ["hel\"lo${trailing}\""]+ },+ {+ "input": "hello\" there \"",+ "word": "hello\" there \"",+ "words": ["hello\" there \""]+ },+ {+ "input": "hello there",+ "word": "hello there",+ "words": ["hello", "there"]+ },+ {+ "input": "hello\\ there",+ "word": "hello there",+ "words": ["hello there"]+ },+ {+ "input": "hello\" there",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "hello\\\" there",+ "word": "hello\" there",+ "words": ["hello\"", "there"]+ },+ {+ "input": "hello\"\\\\there\"",+ "word": "hello\"\\there\"",+ "words": ["hello\"\\there\""]+ },+ {+ "input": "hello\"\\there\"",+ "word": "hello\"\\there\"",+ "words": ["hello\"\\there\""]+ },+ {+ "input": "hello'\\\\there'",+ "word": "hello'\\\\there'",+ "words": ["hello'\\\\there'"]+ },+ {+ "input": "hello'\\there'",+ "word": "hello'\\there'",+ "words": ["hello'\\there'"]+ },+ {+ "input": "hello'$there'",+ "word": "hello'$there'",+ "words": ["hello'$there'"]+ }+]diff --git a/packages/dockerfile-utils-js/tests/lexer.test.ts b/packages/dockerfile-utils-js/tests/lexer.test.tsnew file mode 100644index 000000000..9d2f78b17--- /dev/null+++ b/packages/dockerfile-utils-js/tests/lexer.test.ts@@ -0,0 +1,81 @@+import { assert, describe, test } from 'vitest'++import { ShellLex, isSpace } from '../src'++describe('ShellLex', () => {+ const lex = new ShellLex('\\')++ test('splits words and strips quotes', () => {+ assert.deepEqual(lex.processWords('KEY="a b" OTHER=c'), [+ 'KEY=a b',+ 'OTHER=c',+ ])+ assert.deepEqual(lex.processWords('a "b c" d\\ e'), ['a', 'b c', 'd e'])+ })++ test('preserves variable references', () => {+ assert.deepEqual(lex.processWords('"$HOME"/x'), ['$HOME/x'])+ assert.deepEqual(lex.processWords("'$HOME'"), ['$HOME'])+ assert.deepEqual(lex.processWords('${V//a/b}'), ['${V//a/b}'])+ assert.deepEqual(lex.processWords('a\\$b'), ['a$b'])+ })++ test('expands variables from env', () => {+ const env = new Map([+ ['V', 'a/b/c'],+ ['E', ''],+ ])+ const lex = new ShellLex('\\', { env })+ assert.equal(lex.processWord('$V-${V}-"$V"'), 'a/b/c-a/b/c-a/b/c')+ assert.equal(+ lex.processWord('${V:-x}${E:-x}${E-x}${U:-x}'),+ 'a/b/cx${U:-x}'+ )+ assert.equal(lex.processWord('${V:+y}${E:+y}${E+y}${U+y}'), 'yy${U+y}')+ assert.equal(lex.processWord('${V:?}${U:?msg}'), 'a/b/c${U:?msg}')+ assert.throws(() => lex.processWord('${E:?empty}'), /E: empty/)+ assert.equal(lex.processWord('${V#*/} ${V##*/}'), 'b/c c')+ assert.equal(lex.processWord('${V%/*} ${V%%/*}'), 'a/b a')+ assert.equal(+ lex.processWord('${V/b/x} ${V//\\//-} ${V/?/x}'),+ 'a/x/c a-b-c x/b/c'+ )+ assert.equal(lex.processWord('$U ${U} ${U/a/b}'), '$U ${U} ${U/a/b}')+ assert.equal(+ new ShellLex('\\', { env, skipUnsetEnv: false }).processWord(+ '$U-${U:-d}'+ ),+ '-d'+ )+ })++ test('keeps heredoc markers intact', () => {+ assert.deepEqual(lex.processWords('<<EOF cat'), ['<<EOF', 'cat'])+ })++ test('honours the escape token', () => {+ assert.equal(new ShellLex('`').processWord('a`"b'), 'a"b')+ })++ test('raw modes keep quotes and escapes', () => {+ assert.equal(+ new ShellLex('\\', { rawQuotes: true }).processWord('"a b"'),+ '"a b"'+ )+ assert.equal(+ new ShellLex('\\', { rawEscapes: true }).processWord('a\\"b'),+ 'a\\"b'+ )+ })++ test('rejects unterminated quotes', () => {+ assert.throws(() => lex.processWord('"unterminated'), /double-quote/)+ assert.throws(() => lex.processWord("x 'y"), /single-quote/)+ })+})++test('isSpace', () => {+ assert.isTrue(isSpace(' '))+ assert.isTrue(isSpace('\u00a0'))+ assert.isFalse(isSpace('a'))+})diff --git a/packages/dockerfile-utils-js/tests/moby-patternmatcher.test.ts b/packages/dockerfile-utils-js/tests/moby-patternmatcher.test.tsnew file mode 100644index 000000000..c52e4c85a--- /dev/null+++ b/packages/dockerfile-utils-js/tests/moby-patternmatcher.test.ts@@ -0,0 +1,330 @@+import { assert, describe, test } from 'vitest'++import { PatternMatcher } from '../src'++// Port of moby/patternmatcher v0.6.1 `patternmatcher_test.go` and+// `ignorefile/ignorefile_test.go`. `Matches`, `MatchesOrParentMatches`,+// `MatchesUsingParentResult(s)` all map to `PatternMatcher.matches`.++function matches(text: string, patterns: string[]): boolean {+ return new PatternMatcher(patterns).matches(text)+}++// [pattern, text, pass]+const matchesTests: [string, string, boolean][] = [+ ['**', 'file', true],+ ['**', 'file/', true],+ ['**/', 'file', true], // weird one+ ['**/', 'file/', true],+ ['**', '/', true],+ ['**/', '/', true],+ ['**', 'dir/file', true],+ ['**/', 'dir/file', true],+ ['**', 'dir/file/', true],+ ['**/', 'dir/file/', true],+ ['**/**', 'dir/file', true],+ ['**/**', 'dir/file/', true],+ ['dir/**', 'dir/file', true],+ ['dir/**', 'dir/file/', true],+ ['dir/**', 'dir/dir2/file', true],+ ['dir/**', 'dir/dir2/file/', true],+ ['**/dir', 'dir', true],+ ['**/dir', 'dir/file', true],+ ['**/dir2/*', 'dir/dir2/file', true],+ ['**/dir2/*', 'dir/dir2/file/', true],+ ['**/dir2/**', 'dir/dir2/dir3/file', true],+ ['**/dir2/**', 'dir/dir2/dir3/file/', true],+ ['**file', 'file', true],+ ['**file', 'dir/file', true],+ ['**/file', 'dir/file', true],+ ['**file', 'dir/dir/file', true],+ ['**/file', 'dir/dir/file', true],+ ['**/file*', 'dir/dir/file', true],+ ['**/file*', 'dir/dir/file.txt', true],+ ['**/file*txt', 'dir/dir/file.txt', true],+ ['**/file*.txt', 'dir/dir/file.txt', true],+ ['**/file*.txt*', 'dir/dir/file.txt', true],+ ['**/**/*.txt', 'dir/dir/file.txt', true],+ ['**/**/*.txt2', 'dir/dir/file.txt', false],+ ['**/*.txt', 'file.txt', true],+ ['**/**/*.txt', 'file.txt', true],+ ['a**/*.txt', 'a/file.txt', true],+ ['a**/*.txt', 'a/dir/file.txt', true],+ ['a**/*.txt', 'a/dir/dir/file.txt', true],+ ['a/*.txt', 'a/dir/file.txt', false],+ ['a/*.txt', 'a/file.txt', true],+ ['a/*.txt**', 'a/file.txt', true],+ ['a[b-d]e', 'ae', false],+ ['a[b-d]e', 'ace', true],+ ['a[b-d]e', 'aae', false],+ ['a[^b-d]e', 'aze', true],+ ['.*', '.foo', true],+ ['.*', 'foo', false],+ ['abc.def', 'abcdef', false],+ ['abc.def', 'abc.def', true],+ ['abc.def', 'abcZdef', false],+ ['abc?def', 'abcZdef', true],+ ['abc?def', 'abcdef', false],+ ['a\\\\', 'a\\', true],+ ['**/foo/bar', 'foo/bar', true],+ ['**/foo/bar', 'dir/foo/bar', true],+ ['**/foo/bar', 'dir/dir2/foo/bar', true],+ ['abc/**', 'abc', false],+ ['abc/**', 'abc/def', true],+ ['abc/**', 'abc/def/ghi', true],+ ['**/.foo', '.foo', true],+ ['**/.foo', 'bar.foo', false],+ ['a(b)c/def', 'a(b)c/def', true],+ ['a(b)c/def', 'a(b)c/xyz', false],+ ['a.|)$(}+{bc', 'a.|)$(}+{bc', true],+ [+ 'dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl',+ 'dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl',+ true,+ ],+ [+ 'dist/*.whl',+ 'dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl',+ true,+ ],+ // non-windows only upstream+ ['a\\*b', 'a*b', true],+]++// [patterns, text, pass]+const multiPatternTests: [string[], string, boolean][] = [+ [['**', '!util/docker/web'], 'util/docker/web/foo', false],+ [+ ['**', '!util/docker/web', 'util/docker/web/foo'],+ 'util/docker/web/foo',+ true,+ ],+ [+ ['**', '!dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl'],+ 'dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl',+ false,+ ],+ [+ ['**', '!dist/*.whl'],+ 'dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl',+ false,+ ],+]++// [pattern, s, match, bad pattern]+const matchTests: [string, string, boolean, boolean][] = [+ ['abc', 'abc', true, false],+ ['*', 'abc', true, false],+ ['*c', 'abc', true, false],+ ['a*', 'a', true, false],+ ['a*', 'abc', true, false],+ ['a*', 'ab/c', true, false],+ ['a*/b', 'abc/b', true, false],+ ['a*/b', 'a/c/b', false, false],+ ['a*b*c*d*e*/f', 'axbxcxdxe/f', true, false],+ ['a*b*c*d*e*/f', 'axbxcxdxexxx/f', true, false],+ ['a*b*c*d*e*/f', 'axbxcxdxe/xxx/f', false, false],+ ['a*b*c*d*e*/f', 'axbxcxdxexxx/fff', false, false],+ ['a*b?c*x', 'abxbbxdbxebxczzx', true, false],+ ['a*b?c*x', 'abxbbxdbxebxczzy', false, false],+ ['ab[c]', 'abc', true, false],+ ['ab[b-d]', 'abc', true, false],+ ['ab[e-g]', 'abc', false, false],+ ['ab[^c]', 'abc', false, false],+ ['ab[^b-d]', 'abc', false, false],+ ['ab[^e-g]', 'abc', true, false],+ ['a\\*b', 'a*b', true, false],+ ['a\\*b', 'ab', false, false],+ ['a?b', 'a☺b', true, false],+ ['a[^a]b', 'a☺b', true, false],+ ['a???b', 'a☺b', false, false],+ ['a[^a][^a][^a]b', 'a☺b', false, false],+ ['[a-ζ]*', 'α', true, false],+ ['*[a-ζ]', 'A', false, false],+ ['a?b', 'a/b', false, false],+ ['a*b', 'a/b', false, false],+ ['[\\]a]', ']', true, false],+ ['[\\-]', '-', true, false],+ ['[x\\-]', 'x', true, false],+ ['[x\\-]', '-', true, false],+ ['[x\\-]', 'z', false, false],+ ['[\\-x]', 'x', true, false],+ ['[\\-x]', '-', true, false],+ ['[\\-x]', 'a', false, false],+ ['[]a]', ']', false, true],+ ['[-]', '-', false, true],+ ['[x-]', 'x', false, true],+ ['[x-]', '-', false, true],+ ['[x-]', 'z', false, true],+ ['[-x]', 'x', false, true],+ ['[-x]', '-', false, true],+ ['[-x]', 'a', false, true],+ ['\\', 'a', false, true],+ ['[a-b-c]', 'a', false, true],+ ['[', 'a', false, true],+ ['[^', 'a', false, true],+ ['[^bc', 'a', false, true],+ ['a[', 'a', false, true],+ ['a[', 'ab', false, true],+ ['*x', 'xxx', true, false],+]++describe('moby/patternmatcher', () => {+ test('TestWildcardMatches', () => {+ assert.isTrue(matches('fileutils.go', ['*']))+ })++ test('TestPatternMatches', () => {+ assert.isTrue(matches('fileutils.go', ['*.go']))+ })++ test('TestExclusionPatternMatchesPatternBefore', () => {+ assert.isTrue(matches('fileutils.go', ['!fileutils.go', '*.go']))+ })++ test('TestPatternMatchesFolderExclusions', () => {+ assert.isFalse(matches('docs/README.md', ['docs', '!docs/README.md']))+ })++ test('TestPatternMatchesFolderWithSlashExclusions', () => {+ assert.isFalse(matches('docs/README.md', ['docs/', '!docs/README.md']))+ })++ test('TestPatternMatchesFolderWildcardExclusions', () => {+ assert.isFalse(matches('docs/README.md', ['docs/*', '!docs/README.md']))+ })++ test('TestExclusionPatternMatchesPatternAfter', () => {+ assert.isFalse(matches('fileutils.go', ['*.go', '!fileutils.go']))+ })++ test('TestExclusionPatternMatchesWholeDirectory', () => {+ assert.isFalse(matches('.', ['*.go']))+ })++ test('TestSingleExclamationError', () => {+ assert.throws(() => matches('fileutils.go', ['!']), /illegal exclusion/)+ })++ test('TestMatchesWithNoPatterns', () => {+ assert.isFalse(matches('/any/path/there', []))+ })++ test('TestMatchesWithMalformedPatterns', () => {+ assert.throws(() => matches('/any/path/there', ['[']))+ })++ describe('TestMatches', () => {+ test.each(matchesTests)('%j matches %j -> %s', (pattern, text, pass) => {+ assert.strictEqual(matches(text, [pattern]), pass)+ })++ test.each(multiPatternTests)(+ '%j matches %j -> %s',+ (patterns, text, pass) => {+ assert.strictEqual(matches(text, patterns), pass)+ }+ )++ // Upstream runs the same table on Windows, where `filepath.Clean` turns+ // the slashes into backslashes+ const windowsTests = matchesTests.filter(([p]) => !p.includes('\\'))+ test.each(windowsTests)(+ 'windows: %j matches %j -> %s',+ (pattern, text, pass) => {+ const matcher = new PatternMatcher([pattern.replaceAll('/', '\\')], {+ backslashIsSeparator: true,+ })+ assert.strictEqual(matcher.matches(text.replaceAll('/', '\\')), pass)+ }+ )+ })++ test('TestCleanPatterns', () => {+ assert.lengthOf(new PatternMatcher(['docs', 'config']).patterns, 2)+ })++ test('TestCleanPatternsStripEmptyPatterns', () => {+ assert.lengthOf(new PatternMatcher(['docs', 'config', '']).patterns, 2)+ })++ test('TestCleanPatternsExceptionFlag', () => {+ const matcher = new PatternMatcher(['docs', '!docs/README.md'])+ assert.deepEqual(matcher.patterns, ['docs', '!docs/README.md'])+ })++ test('TestCleanPatternsLeadingSpaceTrimmed', () => {+ const matcher = new PatternMatcher(['docs', ' !docs/README.md'])+ assert.deepEqual(matcher.patterns, ['docs', '!docs/README.md'])+ })++ test('TestCleanPatternsTrailingSpaceTrimmed', () => {+ const matcher = new PatternMatcher(['docs', '!docs/README.md '])+ assert.deepEqual(matcher.patterns, ['docs', '!docs/README.md'])+ })++ test('TestCleanPatternsErrorSingleException', () => {+ assert.throws(() => new PatternMatcher(['!']), /illegal exclusion/)+ })++ describe('TestMatch', () => {+ test.each(matchTests)(+ '%j matches %j -> %s (bad pattern: %s)',+ (pattern, s, match, bad) => {+ if (bad) {+ assert.throws(() => new PatternMatcher([pattern]), /syntax error/)+ return+ }+ assert.strictEqual(matches(s, [pattern]), match)+ }+ )++ // On Windows upstream skips the patterns containing backslashes+ const windowsTests = matchTests.filter(([p]) => !p.includes('\\'))+ test.each(windowsTests)(+ 'windows: %j matches %j -> %s (bad pattern: %s)',+ (pattern, s, match, bad) => {+ const create = () =>+ new PatternMatcher([pattern.replaceAll('/', '\\')], {+ backslashIsSeparator: true,+ })+ if (bad) {+ assert.throws(create, /syntax error/)+ return+ }+ assert.strictEqual(create().matches(s.replaceAll('/', '\\')), match)+ }+ )+ })++ test('TestMatchesOrParentMatchesMalformedPatternDoesNotPanicOnRepeatedCall', () => {+ // Upstream only fails when matching; the patterns are compiled upfront+ // here so the bad range is reported when the matcher is created+ assert.throws(() => new PatternMatcher(['[Local-Only]/']))+ assert.throws(() => new PatternMatcher(['[Local-Only]/']))+ })++ test('ignorefile TestReadAll', () => {+ const content = [+ 'test1',+ '/test2',+ '/a/file/here',+ '',+ 'lastfile',+ '# this is a comment',+ ' # not a comment',+ '! /inverted/abs/path',+ ]+ assert.deepEqual(new PatternMatcher(content).patterns, [+ 'test1',+ 'test2',+ 'a/file/here',+ 'lastfile',+ '# not a comment',+ '!inverted/abs/path',+ ])+ // Upstream `ReadAll` keeps `!` and `! ` as `!`, which `New` then rejects+ assert.throws(() => new PatternMatcher([...content, '!']))+ assert.throws(() => new PatternMatcher([...content, '! ']))+ })+})diff --git a/packages/dockerfile-utils-js/tests/syntax.test.ts b/packages/dockerfile-utils-js/tests/syntax.test.tsnew file mode 100644index 000000000..c0c943f39--- /dev/null+++ b/packages/dockerfile-utils-js/tests/syntax.test.ts@@ -0,0 +1,155 @@+import { assert, describe, test } from 'vitest'++import {+ DockerfileSyntaxError,+ chompHeredocContent,+ parseDockerfileAst,+ parseHeredoc,+ parseWords,+} from '../src'++describe('parseDockerfileAst', () => {+ test('upper-cases instruction names and keeps argument casing', () => {+ const ast = parseDockerfileAst('from node:24 as build\n')+ assert.equal(ast.escapeToken, '\\')+ assert.lengthOf(ast.instructions, 1)+ assert.equal(ast.instructions[0].name, 'FROM')+ assert.deepEqual(ast.instructions[0].args, ['node:24', 'as', 'build'])+ assert.isFalse(ast.instructions[0].json)+ })++ test('honours the escape directive', () => {+ const ast = parseDockerfileAst('# escape=`\nFROM a\nRUN echo a `\n b\n')+ assert.equal(ast.escapeToken, '`')+ const run = ast.instructions[1]+ assert.deepEqual(run.args, ['echo a b'])+ assert.equal(run.startLine, 3)+ assert.equal(run.endLine, 4)+ })++ test('drops comments inside continuations', () => {+ const ast = parseDockerfileAst(+ 'FROM a\nRUN apt-get update \\\n # comment\n && apt-get install -y curl\n'+ )+ assert.deepEqual(ast.instructions[1].args, [+ 'apt-get update && apt-get install -y curl',+ ])+ })++ test('parses JSON form', () => {+ const ast = parseDockerfileAst('FROM a\nCMD ["a", "b c"]\n')+ assert.isTrue(ast.instructions[1].json)+ assert.deepEqual(ast.instructions[1].args, ['a', 'b c'])+ })++ test('separates builder flags from arguments', () => {+ const ast = parseDockerfileAst(+ 'FROM a\nCOPY --chown=1:1 --chmod=755 a b /d\n'+ )+ assert.deepEqual(ast.instructions[1].flags, ['--chown=1:1', '--chmod=755'])+ assert.deepEqual(ast.instructions[1].args, ['a', 'b', '/d'])+ })++ test('parses ENV key/value and legacy forms into triples', () => {+ const ast = parseDockerfileAst(+ 'FROM a\nENV A=1 B="x y"\nENV LEGACY some value\n'+ )+ assert.deepEqual(ast.instructions[1].args, [+ 'A',+ '1',+ '=',+ 'B',+ '"x y"',+ '=',+ ])+ assert.deepEqual(ast.instructions[2].args, ['LEGACY', 'some value', ''])+ })++ test('collects heredocs', () => {+ const ast = parseDockerfileAst(+ "FROM a\nRUN <<EOF\necho hi\nEOF\nRUN <<-'EOT' cat\n\thi\nEOT\n"+ )+ const [, first, second] = ast.instructions+ assert.deepEqual(first.args, ['<<EOF'])+ assert.deepEqual(first.heredocs, [+ {+ name: 'EOF',+ content: 'echo hi\n',+ chomp: false,+ expand: true,+ fileDescriptor: 0,+ },+ ])+ assert.equal(first.endLine, 4)+ assert.deepEqual(second.heredocs, [+ {+ name: 'EOT',+ content: '\thi\n',+ chomp: true,+ expand: false,+ fileDescriptor: 0,+ },+ ])+ })++ test('strips a BOM', () => {+ const ast = parseDockerfileAst('\ufeffFROM a\n')+ assert.equal(ast.instructions[0].name, 'FROM')+ })++ test('warns about empty continuation lines', () => {+ const ast = parseDockerfileAst('FROM a\nRUN a \\\n\nb\n')+ assert.deepEqual(ast.instructions[1].args, ['a b'])+ assert.lengthOf(ast.warnings, 1)+ assert.match(ast.warnings[0].message, /Empty continuation line/)+ })++ test('tolerates a trailing continuation at EOF', () => {+ const ast = parseDockerfileAst('FROM a\nRUN echo \\\n')+ assert.deepEqual(ast.instructions[1].args, ['echo'])+ })++ test('accepts empty and comment-only input', () => {+ assert.lengthOf(parseDockerfileAst('').instructions, 0)+ assert.lengthOf(parseDockerfileAst('# only comment\n').instructions, 0)+ })++ test('rejects unknown instructions with a line number', () => {+ assert.throws(+ () => parseDockerfileAst('FROM a\nRNU x\n'),+ DockerfileSyntaxError,+ /line 2: unknown instruction: RNU/+ )+ })+})++test('parseHeredoc', () => {+ assert.equal(parseHeredoc('<<' + ' '.repeat(50_000) + '<'), undefined)+ assert.equal(parseHeredoc('\u00b2<<EOF'), undefined)+ assert.equal(parseHeredoc('<<' + ' '.repeat(50_000)), undefined)+ assert.deepEqual(parseHeredoc('<<-EOF'), {+ name: 'EOF',+ content: '',+ chomp: true,+ expand: true,+ fileDescriptor: 0,+ })+ assert.deepEqual(parseHeredoc("<<'EOF'"), {+ name: 'EOF',+ content: '',+ chomp: false,+ expand: false,+ fileDescriptor: 0,+ })+ assert.equal(parseHeredoc('3<<EOF')?.fileDescriptor, 3)+ assert.isUndefined(parseHeredoc('<<'))+ assert.isUndefined(parseHeredoc('abc'))+})++test('chompHeredocContent strips leading tabs', () => {+ assert.equal(chompHeredocContent('\thi\n\t\tthere\n'), 'hi\nthere\n')+})++test('parseWords keeps quotes and escapes', () => {+ assert.deepEqual(parseWords('a "b c" d\\ e', '\\'), ['a', '"b c"', 'd\\ e'])+})diff --git a/packages/dockerfile-utils-js/tsconfig.json b/packages/dockerfile-utils-js/tsconfig.jsonnew file mode 100644index 000000000..ff09139d6--- /dev/null+++ b/packages/dockerfile-utils-js/tsconfig.json@@ -0,0 +1,8 @@+{+ "extends": "../../tsconfig.sdk.json",+ "compilerOptions": {+ "outDir": "dist"+ },+ "include": ["src"],+ "exclude": ["dist", "node_modules", "tsdown.config.ts"]+}diff --git a/packages/dockerfile-utils-js/tsdown.config.ts b/packages/dockerfile-utils-js/tsdown.config.tsnew file mode 100644index 000000000..3a056f888--- /dev/null+++ b/packages/dockerfile-utils-js/tsdown.config.ts@@ -0,0 +1,5 @@+import { defineConfig } from 'tsdown'++import { createSdkTsdownConfig } from '../../tsdown.sdk.config.mts'++export default defineConfig(createSdkTsdownConfig())diff --git a/packages/dockerfile-utils-js/vitest.config.mts b/packages/dockerfile-utils-js/vitest.config.mtsnew file mode 100644index 000000000..9b7555029--- /dev/null+++ b/packages/dockerfile-utils-js/vitest.config.mts@@ -0,0 +1,10 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ include: ['tests/**/*.test.ts'],+ globals: false,+ environment: 'node',+ testTimeout: 10_000,+ },+})diff --git a/packages/dockerfile-utils-python/LICENSE b/packages/dockerfile-utils-python/LICENSEnew file mode 100644index 000000000..ec47fef19--- /dev/null+++ b/packages/dockerfile-utils-python/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2023 FoundryLabs, Inc.++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/dockerfile-utils-python/Makefile b/packages/dockerfile-utils-python/Makefilenew file mode 100644index 000000000..72729c985--- /dev/null+++ b/packages/dockerfile-utils-python/Makefile@@ -0,0 +1,13 @@+typecheck:+ ty check e2b_dockerfile_utils++lint:+ ruff check .+ ruff format --check .++format:+ ruff format .++.PHONY: test+test:+ uv run pytest --verbosediff --git a/packages/dockerfile-utils-python/NOTICE b/packages/dockerfile-utils-python/NOTICEnew file mode 100644index 000000000..179a09761--- /dev/null+++ b/packages/dockerfile-utils-python/NOTICE@@ -0,0 +1,11 @@+E2B Dockerfile utils+Copyright 2025 FoundryLabs, Inc.++This product includes software derived from moby/buildkit+(https://github.com/moby/buildkit), licensed under the Apache License 2.0:+the Dockerfile parser and shell lexer are ported from frontend/dockerfile.++This product includes software derived from moby/patternmatcher+(https://github.com/moby/patternmatcher), licensed under the Apache License 2.0.+Copyright 2012-2017 Docker, Inc.+This product includes software developed at Docker, Inc. (https://www.docker.com).diff --git a/packages/dockerfile-utils-python/README.md b/packages/dockerfile-utils-python/README.mdnew file mode 100644index 000000000..87461164c--- /dev/null+++ b/packages/dockerfile-utils-python/README.md@@ -0,0 +1,36 @@+# e2b-dockerfile-utils++Dockerfile parser and shell lexer ported from [BuildKit](https://github.com/moby/buildkit/tree/master/frontend/dockerfile) and a `.dockerignore` matcher ported from [moby/patternmatcher](https://github.com/moby/patternmatcher), with no runtime dependencies. Used by the [E2B SDK](https://pypi.org/project/e2b/) to implement `Template.from_dockerfile` and to filter the build context.++```python+from e2b_dockerfile_utils import ShellLex, parse_dockerfile_ast++ast = parse_dockerfile_ast(+ """+FROM node:24 AS build+ENV KEY="a b" OTHER=c+RUN <<EOF+npm ci+npm run build+EOF+"""+)++for instruction in ast.instructions:+ print(instruction.name, instruction.flags, instruction.args)++lex = ShellLex(ast.escape_token)+lex.process_words('KEY="a b" OTHER=c') # ['KEY=a b', 'OTHER=c']+```++`parse_dockerfile_ast` handles parser directives (`# escape=`, `# syntax=`), comments (including inside line continuations), builder flags, JSON/exec forms and heredocs, and reports line numbers and warnings. `ShellLex` splits and unquotes words the way BuildKit does, preserving `$VAR` / `${VAR:-default}` references for later expansion.++```python+from e2b_dockerfile_utils import PatternMatcher++matcher = PatternMatcher(["node_modules", "*.log", "!keep.log"])+matcher.matches("node_modules/pkg/index.js") # True+matcher.matches("keep.log") # False+```++`PatternMatcher` applies `.dockerignore` semantics to slash-separated paths relative to the context root: a pattern matching a directory excludes everything under it, and `!` patterns re-include paths (the last matching pattern wins). An invalid pattern raises a plain `ValueError`.diff --git a/packages/dockerfile-utils-python/e2b_dockerfile_utils/__init__.py b/packages/dockerfile-utils-python/e2b_dockerfile_utils/__init__.pynew file mode 100644index 000000000..7c470be95--- /dev/null+++ b/packages/dockerfile-utils-python/e2b_dockerfile_utils/__init__.py@@ -0,0 +1,28 @@+from e2b_dockerfile_utils.dockerignore import PatternMatcher+from e2b_dockerfile_utils.lexer import ShellLex, is_space+from e2b_dockerfile_utils.syntax import (+ DockerfileAst,+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileSyntaxError,+ DockerfileWarning,+ chomp_heredoc_content,+ parse_dockerfile_ast,+ parse_heredoc,+ parse_words,+)++__all__ = [+ "DockerfileAst",+ "DockerfileHeredoc",+ "DockerfileInstruction",+ "DockerfileSyntaxError",+ "DockerfileWarning",+ "PatternMatcher",+ "ShellLex",+ "chomp_heredoc_content",+ "is_space",+ "parse_dockerfile_ast",+ "parse_heredoc",+ "parse_words",+]diff --git a/packages/python-sdk/e2b/template/dockerignore.py b/packages/dockerfile-utils-python/e2b_dockerfile_utils/dockerignore.pysimilarity index 64%rename from packages/python-sdk/e2b/template/dockerignore.pyrename to packages/dockerfile-utils-python/e2b_dockerfile_utils/dockerignore.pyindex 5a02be1d9..18e6d7448 100644--- a/packages/python-sdk/e2b/template/dockerignore.py+++ b/packages/dockerfile-utils-python/e2b_dockerfile_utils/dockerignore.py@@ -6,18 +6,14 @@ Port of the pattern matcher from moby/patternmatcher (Apache-2.0):https://github.com/moby/patternmatcher"""-import osimport posixpathimport refrom enum import Enumfrom typing import Callable, 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 == "\\"class _MatchType(Enum):@@ -28,13 +24,54 @@ class _MatchType(Enum):def _clean(pattern: str) -> str:- # Equivalent of Go's filepath.Clean followed by filepath.ToSlash- if _BACKSLASH_IS_SEPARATOR:- pattern = pattern.replace("\\", "/")+ # Equivalent of Go's filepath.Clean on a slash-separated pathreturn posixpath.normpath(re.sub("/+", "/", pattern))-def _compile(pattern: str) -> Callable[[str], bool]:+_BAD_PATTERN = "syntax error in pattern"+++def _class_char(pattern: str, i: int, backslash_is_escape: bool) -> int:+ # Advances over one (possibly escaped) character of a bracket expression+ n = len(pattern)+ if i >= n or pattern[i] in "-]":+ raise ValueError(_BAD_PATTERN)+ if pattern[i] == "\\" and backslash_is_escape:+ i += 1+ if i >= n:+ raise ValueError(_BAD_PATTERN)+ i += 1+ if i >= n:+ raise ValueError(_BAD_PATTERN)+ return i+++def _validate_pattern(pattern: str, backslash_is_escape: bool) -> None:+ # Rejects what Go's filepath.Match rejects (Docker validates patterns with+ # it), as regex engines are more lenient about bracket expressions+ n = len(pattern)+ i = 0+ while i < n:+ ch = pattern[i]+ i += 1+ if ch == "\\" and backslash_is_escape:+ if i >= n:+ raise ValueError(_BAD_PATTERN)+ i += 1+ elif ch == "[":+ if i < n and pattern[i] == "^":+ i += 1+ ranges = 0+ while not (ranges > 0 and i < n and pattern[i] == "]"):+ i = _class_char(pattern, i, backslash_is_escape)+ if pattern[i] == "-":+ i = _class_char(pattern, i + 1, backslash_is_escape)+ ranges += 1+ i += 1+++def _compile(pattern: str, backslash_is_escape: bool) -> Callable[[str], bool]:+ _validate_pattern(pattern, backslash_is_escape)# Like moby, use plain string checks for patterns without wildcards and# only fall back to a regex otherwiseregex = "^"@@ -74,7 +111,7 @@ def _compile(pattern: str) -> Callable[[str], bool]:if j < n and pattern[j] == "^":j += 1while j < n and pattern[j] != "]":- if pattern[j] == "\\" and not _BACKSLASH_IS_SEPARATOR:+ if pattern[j] == "\\" and backslash_is_escape:j += 1j += 1regex += pattern[i - 1 : j + 1]@@ -85,7 +122,7 @@ def _compile(pattern: str) -> Callable[[str], bool]:match_type = _MatchType.REGEXelif ch in _LITERAL_REGEX_CHARS:regex += "\\" + ch- elif ch == "\\" and not _BACKSLASH_IS_SEPARATOR:+ elif ch == "\\" and backslash_is_escape:# Escape the next characterif i < n:regex += re.escape(pattern[i])@@ -112,10 +149,12 @@ def _compile(pattern: str) -> Callable[[str], bool]:class _Pattern:- def __init__(self, cleaned_pattern: str, exclusion: bool):+ def __init__(+ self, cleaned_pattern: str, exclusion: bool, backslash_is_escape: bool+ ):self.exclusion = exclusionself.dirs = cleaned_pattern.split("/")- self.match = _compile(cleaned_pattern)+ self.match = _compile(cleaned_pattern, backslash_is_escape)class PatternMatcher:@@ -125,28 +164,53 @@ class PatternMatcher:A pattern that matches a directory excludes everything under it, a leading`/` is ignored, and `!` patterns re-include paths (the last matchingpattern wins).++ :param patterns: Patterns in `.dockerignore` syntax+ :param backslash_is_separator: Whether `\\` separates path segments+ (as on Windows) instead of escaping the next character in a pattern+ :raises ValueError: If a pattern is invalid, such as an unterminated `[`"""- def __init__(self, patterns: List[str]):+ def __init__(self, patterns: List[str], backslash_is_separator: bool = False):self._patterns: List[_Pattern] = []+ self._cleaned: List[str] = []+ self._backslash_is_separator = backslash_is_separatorfor original in patterns:+ if original.startswith("#"):+ continuepattern = original.strip()- if not pattern or pattern.startswith("#"):+ if not pattern:continueexclusion = pattern.startswith("!")if exclusion:pattern = pattern[1:].strip()if not pattern:- continue+ raise ValueError(+ f"Invalid ignore pattern '{original}': illegal exclusion pattern"+ )+ if backslash_is_separator:+ pattern = pattern.replace("\\", "/")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+ self._patterns.append(+ _Pattern(pattern, exclusion, not backslash_is_separator)+ )+ except (re.error, ValueError) as e:+ raise ValueError(f"Invalid ignore pattern '{original}': {e}") from e+ self._cleaned.append(("!" if exclusion else "") + pattern)++ @property+ def patterns(self) -> List[str]:+ """+ The cleaned patterns, `!` prefixed for exclusions. Empty lines and+ comments are dropped.+ """+ return list(self._cleaned)++ def _to_slash(self, path: str) -> str:+ return path.replace("\\", "/") if self._backslash_is_separator else pathdef matches(self, path: str) -> bool:"""@@ -157,7 +221,7 @@ class PatternMatcher::param path: Slash-separated path relative to the context root:return: True if the path is excluded"""- segments = path.split("/")+ segments = self._to_slash(path).split("/")parent_matched: List[bool] = []matched = Falsefor depth in range(1, len(segments) + 1):@@ -187,7 +251,7 @@ class PatternMatcher::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("/")+ dir_segments = self._to_slash(dir_path).split("/")for pattern in self._patterns:if pattern.exclusion and self._may_match_under(pattern, dir_segments):return Truediff --git a/packages/dockerfile-utils-python/e2b_dockerfile_utils/lexer.py b/packages/dockerfile-utils-python/e2b_dockerfile_utils/lexer.pynew file mode 100644index 000000000..b5031378b--- /dev/null+++ b/packages/dockerfile-utils-python/e2b_dockerfile_utils/lexer.py@@ -0,0 +1,483 @@+"""+Shell-style word lexer for Dockerfile instruction arguments.++This is a port of BuildKit's ``frontend/dockerfile/shell`` lexer+(https://github.com/moby/buildkit). Variable references (``$VAR``,+``${VAR:-default}``, ...) are expanded from the ``env`` mapping; without it+they are kept verbatim, so they can be evaluated later inside the sandbox.+"""++import re+import unicodedata+from typing import Callable, List, Mapping, Optional, Tuple++_SPECIAL_PARAMS = "@*#?-$!0"+_ASCII_SPACES = " \t\n\v\f\r\x85\xa0"+++def is_space(ch: str) -> bool:+ """Equivalent of Go's ``unicode.IsSpace``."""+ return ch in _ASCII_SPACES or unicodedata.category(ch).startswith("Z")+++def _is_letter(ch: str) -> bool:+ return ch.isalpha()+++def _is_digit(ch: str) -> bool:+ return ch.isdecimal()+++class _Scanner:+ def __init__(self, text: str) -> None:+ self._chars = text+ self._pos = 0++ def peek(self) -> Optional[str]:+ if self._pos < len(self._chars):+ return self._chars[self._pos]+ return None++ def next(self) -> Optional[str]:+ if self._pos < len(self._chars):+ ch = self._chars[self._pos]+ self._pos += 1+ return ch+ return None+++class _Words:+ def __init__(self) -> None:+ self._words: List[str] = []+ self._buf: List[str] = []+ self._in_word = False++ def add_char(self, ch: str) -> None:+ if is_space(ch) and self._in_word:+ if self._buf:+ self._words.append("".join(self._buf))+ self._buf = []+ self._in_word = False+ elif not is_space(ch):+ self.add_raw_char(ch)++ def add_raw_char(self, ch: str) -> None:+ self._buf.append(ch)+ self._in_word = True++ def add_string(self, text: str) -> None:+ for ch in text:+ self.add_char(ch)++ def add_raw_string(self, text: str) -> None:+ self._buf.append(text)+ self._in_word = True++ def get_words(self) -> List[str]:+ if self._buf:+ self._words.append("".join(self._buf))+ self._buf = []+ self._in_word = False+ return self._words+++class ShellLex:+ def __init__(+ self,+ escape_token: str,+ raw_quotes: bool = False,+ raw_escapes: bool = False,+ skip_process_quotes: bool = False,+ env: Optional[Mapping[str, str]] = None,+ skip_unset_env: bool = True,+ ) -> None:+ """+ :param escape_token: Escape character (``\\`` or `````)+ :param raw_quotes: Keep quote characters in the output instead of removing them+ :param raw_escapes: Keep escape characters in the output instead of removing them+ :param skip_process_quotes: Do not treat quote characters specially at all+ :param env: Variables to expand. Defaults to no variables+ :param skip_unset_env: Keep references to variables missing from ``env``+ verbatim instead of expanding them to an empty string+ """+ self._escape_token = escape_token+ self._raw_quotes = raw_quotes+ self._raw_escapes = raw_escapes+ self._skip_process_quotes = skip_process_quotes+ self._env: Mapping[str, str] = env if env is not None else {}+ self._skip_unset_env = skip_unset_env++ def process_word(self, word: str) -> str:+ """Process a single word: remove quotes/escapes, keep whitespace."""+ return self._process(word)[0]++ def process_words(self, word: str) -> List[str]:+ """Process a line into whitespace separated words, honoring quotes."""+ return self._process(word)[1]++ def _process(self, word: str) -> Tuple[str, List[str]]:+ sw = _ShellWord(+ _Scanner(word),+ self._escape_token,+ self._raw_quotes,+ self._raw_escapes,+ self._skip_process_quotes,+ self._env,+ self._skip_unset_env,+ )+ try:+ return sw.process_stop_on(None, self._raw_escapes)+ except (ValueError, RecursionError) as err:+ raise ValueError(f"failed to process {word!r}: {err}") from None+++class _ShellWord:+ def __init__(+ self,+ scanner: _Scanner,+ escape_token: str,+ raw_quotes: bool,+ raw_escapes: bool,+ skip_process_quotes: bool,+ env: Mapping[str, str],+ skip_unset_env: bool,+ ) -> None:+ self._scanner = scanner+ self._escape_token = escape_token+ self._raw_quotes = raw_quotes+ self._raw_escapes = raw_escapes+ self._skip_process_quotes = skip_process_quotes+ self._env = env+ self._skip_unset_env = skip_unset_env++ def process_stop_on(+ self, stop_char: Optional[str], raw_escapes: bool+ ) -> Tuple[str, List[str]]:+ result: List[str] = []+ words = _Words()++ previous_raw_escapes = self._raw_escapes+ self._raw_escapes = raw_escapes+ try:+ while True:+ ch = self._scanner.peek()+ if ch is None:+ break++ if stop_char is not None and ch == stop_char:+ self._scanner.next()+ return "".join(result), words.get_words()++ fn = self._special_handler(ch)+ if fn is not None:+ tmp = fn()+ result.append(tmp)+ if ch == "$":+ words.add_string(tmp)+ else:+ words.add_raw_string(tmp)+ continue++ ch = self._scanner.next()+ assert ch is not None+ if ch == self._escape_token:+ if self._raw_escapes:+ words.add_raw_char(ch)+ result.append(ch)++ # the escape token escapes the next character, except at end of line+ nxt = self._scanner.next()+ if nxt is None:+ break+ ch = nxt+ words.add_raw_char(ch)+ else:+ words.add_char(ch)+ result.append(ch)+ finally:+ self._raw_escapes = previous_raw_escapes++ if stop_char is not None:+ raise ValueError(+ f"unexpected end of statement while looking for matching {stop_char}"+ )+ return "".join(result), words.get_words()++ def _special_handler(self, ch: str) -> Optional[Callable[[], str]]:+ if ch == "$":+ return self._process_dollar+ if ch == "<":+ return self._process_possible_heredoc+ if ch == "'" and not self._skip_process_quotes:+ return self._process_single_quote+ if ch == '"' and not self._skip_process_quotes:+ return self._process_double_quote+ return None++ def _process_single_quote(self) -> str:+ # All chars between single quotes are taken as-is; a single quote+ # cannot be escaped inside single quotes.+ result: List[str] = []+ ch = self._scanner.next()+ assert ch is not None+ if self._raw_quotes:+ result.append(ch)++ while True:+ ch = self._scanner.next()+ if ch is None:+ raise ValueError(+ "unexpected end of statement while looking for matching single-quote"+ )+ if ch == "'":+ if self._raw_quotes:+ result.append(ch)+ return "".join(result)+ result.append(ch)++ def _process_double_quote(self) -> str:+ # All chars up to the next " are taken as-is, even ', except `$`.+ # The escape token only escapes `"`, `$` and itself.+ result: List[str] = []+ opening = self._scanner.next()+ assert opening is not None+ if self._raw_quotes:+ result.append(opening)++ while True:+ peeked = self._scanner.peek()+ if peeked is None:+ raise ValueError(+ "unexpected end of statement while looking for matching double-quote"+ )+ if peeked == '"':+ ch = self._scanner.next()+ assert ch is not None+ if self._raw_quotes:+ result.append(ch)+ return "".join(result)+ if peeked == "$":+ result.append(self._process_dollar())+ continue++ ch = self._scanner.next()+ assert ch is not None+ if ch == self._escape_token:+ if self._raw_escapes:+ result.append(ch)+ after = self._scanner.peek()+ if after is None:+ # ignore escape token at end of word+ continue+ if after in ('"', "$", self._escape_token):+ ch = self._scanner.next()+ assert ch is not None+ result.append(ch)++ def _process_dollar(self) -> str:+ self._scanner.next() # '$'++ if self._scanner.peek() != "{":+ name = self._process_name()+ if name == "":+ return "$"+ value = self._env.get(name)+ if value is None and self._skip_unset_env:+ return "$" + name+ return value or ""++ self._scanner.next() # '{'+ first = self._scanner.peek()+ if first is None:+ raise ValueError("syntax error: missing '}'")+ if first in ("{", "}", ":"):+ raise ValueError("syntax error: bad substitution")++ name = self._process_name()+ ch = self._scanner.next()+ if ch is None:+ raise ValueError("syntax error: missing '}'")+ chs = ch+ value = self._env.get(name)++ if ch == "}":+ if value is None and self._skip_unset_env:+ return "${" + name + "}"+ return value or ""++ null_is_unset = False+ if ch == ":":+ null_is_unset = True+ modifier = self._scanner.next()+ if modifier is None:+ raise ValueError("syntax error: missing '}'")+ ch = modifier+ chs += ch++ if not null_is_unset:+ if ch == "/":+ return self._process_dollar_replace(name)+ if ch not in "+-?#%":+ raise ValueError(f"unsupported modifier ({chs}) in substitution")++ raw_escapes = ch in ("#", "%")+ if null_is_unset and raw_escapes:+ raise ValueError(f"unsupported modifier ({chs}) in substitution")+ word = self._process_stop_on_or_missing_brace("}", raw_escapes)+ if value is None and self._skip_unset_env:+ return "${" + name + chs + word + "}"++ unset = value is None or (null_is_unset and value == "")+ if ch == "-":+ return word if unset else (value or "")+ if ch == "+":+ return "" if unset else word+ if ch == "?":+ if value is None:+ raise ValueError(f"{name}: {word or 'is not allowed to be unset'}")+ if unset:+ raise ValueError(f"{name}: {word or 'is not allowed to be empty'}")+ return value+ if ch in ("#", "%"):+ # `#`/`%` remove the shortest match, `##`/`%%` the longest+ greedy = word.startswith(ch)+ pattern = word[1:] if greedy else word+ if ch == "%":+ return _trim_suffix(pattern, value or "", greedy)+ return _trim_prefix(pattern, value or "", greedy)+ raise ValueError(f"unsupported modifier ({chs}) in substitution")++ def _process_dollar_replace(self, name: str) -> str:+ op = "/"+ if self._scanner.peek() == "/":+ self._scanner.next()+ op = "//"+ try:+ pattern = self.process_stop_on("/", True)[0]+ except ValueError:+ if self._scanner.peek() is None:+ raise ValueError("syntax error: missing '/' in ${}") from None+ raise+ replacement = self._process_stop_on_or_missing_brace("}", True)++ value = self._env.get(name)+ if value is None and self._skip_unset_env:+ return "${" + name + op + pattern + "/" + replacement + "}"+ regex = _shell_pattern_to_regex(pattern, greedy=True, anchored=False)+ return regex.sub(+ lambda _: replacement, value or "", count=0 if op == "//" else 1+ )++ def _process_stop_on_or_missing_brace(+ self, stop_char: str, raw_escapes: bool+ ) -> str:+ try:+ return self.process_stop_on(stop_char, raw_escapes)[0]+ except ValueError:+ if self._scanner.peek() is None:+ raise ValueError("syntax error: missing '}'") from None+ raise++ def _process_name(self) -> str:+ # Read in a name (alphanumeric or _). A leading digit sequence or a+ # special parameter character is a complete name on its own.+ name: List[str] = []+ while True:+ ch = self._scanner.peek()+ if ch is None:+ break+ if not name and _is_digit(ch):+ digits: List[str] = []+ while True:+ d = self._scanner.peek()+ if d is None or not _is_digit(d):+ break+ digits.append(d)+ self._scanner.next()+ return "".join(digits)+ if not name and ch in _SPECIAL_PARAMS:+ self._scanner.next()+ return ch+ if not _is_letter(ch) and not _is_digit(ch) and ch != "_":+ break+ name.append(ch)+ self._scanner.next()+ return "".join(name)++ def _process_possible_heredoc(self) -> str:+ self._scanner.next() # '<'+ if self._scanner.peek() != "<":+ return "<"+ self._scanner.next()++ # a heredoc may have whitespace between `<<` and the terminator word+ space: List[str] = []+ while True:+ ch = self._scanner.peek()+ if ch not in ("\t", "\r", " "):+ break+ space.append(ch)+ self._scanner.next()+ return "<<" + "".join(space)+++def _shell_pattern_to_regex(+ pattern: str, greedy: bool, anchored: bool+) -> "re.Pattern[str]":+ """Convert a shell wildcard pattern (``?`` one character, ``*`` the shortest+ or, when greedy, the longest run) to a regular expression. Bracket+ expressions are not supported, like in BuildKit.+ """+ out = "^" if anchored else ""+ star = ".*" if greedy else ".*?"+ i = 0+ while i < len(pattern):+ ch = pattern[i]+ i += 1+ if ch == "*":+ out += star+ continue+ if ch == "?":+ out += "."+ continue+ if ch == "\\":+ # `}` and `/` are escaped to be part of the `${}` word, the escape+ # itself is not part of the pattern+ nxt = pattern[i] if i < len(pattern) else ""+ if nxt in ("}", "/"):+ continue+ i += 1+ if nxt not in ("*", "?", "\\"):+ raise ValueError(+ f"invalid pattern ({pattern}) in substitution: "+ f"invalid escape '\\{nxt}'"+ )+ ch = nxt+ if ch in "[]{}.+()|^$*?\\":+ out += "\\"+ out += ch+ return re.compile(out)+++def _trim_prefix(pattern: str, value: str, greedy: bool) -> str:+ return _shell_pattern_to_regex(pattern, greedy, anchored=True).sub("", value, 1)+++def _reverse_pattern(pattern: str) -> str:+ """Reverse a pattern without turning ``a\\*c`` into ``c*\\a``."""+ out: List[str] = []+ i = 0+ while i < len(pattern):+ if pattern[i] == "\\" and i + 1 < len(pattern):+ out[0:0] = [pattern[i], pattern[i + 1]]+ i += 2+ else:+ out.insert(0, pattern[i])+ i += 1+ return "".join(out)+++def _trim_suffix(pattern: str, value: str, greedy: bool) -> str:+ # regular expressions cannot find the shortest rightmost match, so both+ # the pattern and the value are reversed to turn it into a leftmost search+ return _trim_prefix(_reverse_pattern(pattern), value[::-1], greedy)[::-1]diff --git a/packages/dockerfile-utils-python/e2b_dockerfile_utils/py.typed b/packages/dockerfile-utils-python/e2b_dockerfile_utils/py.typednew file mode 100644index 000000000..e69de29bbdiff --git a/packages/dockerfile-utils-python/e2b_dockerfile_utils/syntax.py b/packages/dockerfile-utils-python/e2b_dockerfile_utils/syntax.pynew file mode 100644index 000000000..9e510110b--- /dev/null+++ b/packages/dockerfile-utils-python/e2b_dockerfile_utils/syntax.py@@ -0,0 +1,624 @@+"""+Dockerfile syntax parser.++Port of BuildKit's ``frontend/dockerfile/parser`` (https://github.com/moby/buildkit):+handles parser directives (``# escape=``), comments, line continuations,+builder flags (``--chown=...``), JSON/exec forms and heredocs.+"""++import json+import re+from dataclasses import dataclass, field+from typing import Callable, Dict, List, Optional, Set, Tuple++from e2b_dockerfile_utils.lexer import ShellLex, is_space+++@dataclass+class DockerfileHeredoc:+ name: str+ # Raw content including trailing newlines of every line.+ content: str+ # `<<-`: leading tabs are stripped from content lines.+ chomp: bool+ # Unquoted terminator: content is subject to variable expansion.+ expand: bool+ file_descriptor: int+++@dataclass+class DockerfileInstruction:+ # Upper-cased instruction keyword, e.g. `RUN`.+ name: str+ # The full (continuation-joined) instruction line.+ original: str+ # Builder flags, e.g. `--chown=user:group`, with quotes removed.+ flags: List[str]+ # Instruction arguments. For `ENV` and `LABEL` these are+ # `[key, value, delimiter, ...]` triples where delimiter is `=` or ``.+ args: List[str]+ # Arguments were given in JSON (exec) form.+ json: bool+ heredocs: List[DockerfileHeredoc]+ start_line: int+ end_line: int+++@dataclass+class DockerfileWarning:+ message: str+ line: int+++@dataclass+class DockerfileAst:+ instructions: List[DockerfileInstruction]+ escape_token: str+ warnings: List[DockerfileWarning] = field(default_factory=list)+++class DockerfileSyntaxError(ValueError):+ def __init__(self, message: str, line: Optional[int] = None) -> None:+ self.line = line+ if line is None:+ super().__init__(f"Dockerfile parse error: {message}")+ else:+ super().__init__(f"Dockerfile parse error on line {line}: {message}")+++_DEFAULT_ESCAPE_TOKEN = "\\"+_WHITESPACE = re.compile(r"[\t\v\f\r ]+")+_ASCII_DIGITS = "0123456789"+_ASCII_SPACES = "\t\n\f\r "+_DIRECTIVE = re.compile(r"^#\s*([a-zA-Z][a-zA-Z0-9]*)\s*=\s*(.+?)\s*$")+_VALID_DIRECTIVES = {"syntax", "escape", "check"}+_HEREDOC_INSTRUCTIONS = {"ADD", "COPY", "RUN"}+_LINES = re.compile(r"[^\n]*\n|[^\n]+$")++ParsedArgs = Tuple[List[str], bool]+LineParser = Callable[[str, str], ParsedArgs]+++def _trim_newline(line: str) -> str:+ return line.rstrip("\r\n")+++def _trim_leading_whitespace(line: str) -> str:+ i = 0+ while i < len(line) and is_space(line[i]):+ i += 1+ return line[i:]+++def _is_comment(line: str) -> bool:+ return _trim_leading_whitespace(line).startswith("#")+++def _split_lines(content: str) -> List[str]:+ """Split into lines the way a `bufio.Scanner` with newline-preserving split does."""+ return _LINES.findall(content)+++class _Directives:+ def __init__(self) -> None:+ self.escape_token = _DEFAULT_ESCAPE_TOKEN+ self._continuation = self._build_continuation_regex(_DEFAULT_ESCAPE_TOKEN)+ self._done = False+ self._seen: Set[str] = set()++ def possible_parser_directive(self, line: str) -> bool:+ """Returns ``True`` when the line was a parser directive."""+ if self._done:+ return False+ match = _DIRECTIVE.match(line)+ if not match:+ self._done = True+ return False+ key = match.group(1).lower()+ if key not in _VALID_DIRECTIVES:+ self._done = True+ return False+ if key in self._seen:+ raise ValueError(f"only one {key} parser directive can be used")+ self._seen.add(key)+ if key == "escape":+ self._set_escape_token(match.group(2))+ return True++ def trim_continuation(self, line: str) -> Tuple[str, bool]:+ """Returns the line without its continuation token and whether it ended."""+ if self._continuation.search(line):+ return self._continuation.sub(r"\1", line), False+ return line, True++ def _set_escape_token(self, token: str) -> None:+ if token not in ("`", "\\"):+ raise ValueError(f"invalid escape token '{token}' does not match ` or \\")+ self.escape_token = token+ self._continuation = self._build_continuation_regex(token)++ @staticmethod+ def _build_continuation_regex(token: str) -> "re.Pattern[str]":+ t = re.escape(token)+ # The escape token is a line continuation when it is the last+ # non-whitespace character and not itself escaped.+ return re.compile(f"([^{t}]){t}[ \\t]*$|^{t}[ \\t]*$")+++def _parse_string(rest: str, _escape_token: str) -> ParsedArgs:+ return ([] if rest == "" else [rest]), False+++def _parse_ignore(_rest: str, _escape_token: str) -> ParsedArgs:+ return [], False+++def _parse_strings_whitespace_delimited(rest: str, _escape_token: str) -> ParsedArgs:+ if rest == "":+ return [], False+ return _WHITESPACE.split(rest), False+++class _NotJsonArrayError(Exception):+ pass+++class _NotStringArrayError(ValueError):+ pass+++def _parse_json(rest: str) -> List[str]:+ rest = _trim_leading_whitespace(rest)+ if not rest.startswith("["):+ raise _NotJsonArrayError()+ try:+ parsed = json.loads(rest)+ except ValueError:+ raise _NotJsonArrayError() from None+ if not isinstance(parsed, list):+ raise _NotJsonArrayError()+ for item in parsed:+ if not isinstance(item, str):+ raise _NotStringArrayError("Only strings are supported in JSON arrays")+ return parsed+++def _parse_maybe_json(rest: str, _escape_token: str) -> ParsedArgs:+ if rest == "":+ return [], False+ try:+ return _parse_json(rest), True+ except _NotJsonArrayError:+ return [rest], False+++def _parse_health_config(rest: str, escape_token: str) -> ParsedArgs:+ # `HEALTHCHECK [flags] <type> <command>`: the type (`CMD`/`NONE`) is the+ # first argument, the command follows in JSON or shell form+ sep = 0+ while sep < len(rest) and not is_space(rest[sep]):+ sep += 1+ nxt = sep+ while nxt < len(rest) and is_space(rest[nxt]):+ nxt += 1+ if sep == 0:+ return [], False+ args, is_json = _parse_maybe_json(rest[nxt:], escape_token)+ return [rest[:sep], *args], is_json+++def _parse_maybe_json_to_list(rest: str, escape_token: str) -> ParsedArgs:+ try:+ return _parse_json(rest), True+ except _NotJsonArrayError:+ return _parse_strings_whitespace_delimited(rest, escape_token)+++def parse_words(rest: str, escape_token: str) -> List[str]:+ """+ Split a line into whitespace separated words, keeping quotes and escape+ characters in place (they are resolved later by the shell lexer).+ """+ words: List[str] = []+ phase = "spaces"+ quote = ""+ blank_ok = False+ word: List[str] = []+ length = len(rest)+ pos = 0++ while pos <= length:+ ch = rest[pos] if pos < length else ""++ if phase == "spaces":+ if pos == length:+ break+ if is_space(ch):+ pos += 1+ continue+ phase = "word"+ if pos == length:+ if blank_ok or word:+ words.append("".join(word))+ break+ if phase == "word":+ if is_space(ch):+ phase = "spaces"+ if blank_ok or word:+ words.append("".join(word))+ word = []+ blank_ok = False+ pos += 1+ continue+ if ch in ("'", '"'):+ quote = ch+ blank_ok = True+ phase = "quote"+ if ch == escape_token:+ if pos + 1 == length:+ pos += 1+ continue # skip an escape token at end of line+ # outside quotes an escape token always keeps itself and the+ # following character, even if that character is a quote+ word.append(ch)+ pos += 1+ word.append(rest[pos])+ pos += 1+ continue+ word.append(ch)+ pos += 1+ continue+ # phase == "quote"+ if ch == quote:+ phase = "word"+ if ch == escape_token and quote != "'":+ if pos + 1 == length:+ phase = "word"+ pos += 1+ continue # skip the escape token at end+ word.append(ch)+ pos += 1+ word.append(rest[pos])+ pos += 1+ continue+ word.append(ch)+ pos += 1++ return words+++def _parse_maybe_json_to_words(rest: str, escape_token: str) -> ParsedArgs:+ """+ Like ``_parse_maybe_json_to_list``, but the shell form is split with quote+ awareness so that ``COPY "my file.txt" /dest/`` works (Docker only+ supports such paths in JSON form).+ """+ try:+ return _parse_json(rest), True+ except _NotJsonArrayError:+ return parse_words(rest, escape_token), False+++def _parse_name_or_name_val(rest: str, escape_token: str) -> ParsedArgs:+ return parse_words(rest, escape_token), False+++def _parse_name_val(key: str) -> LineParser:+ def parse(rest: str, escape_token: str) -> ParsedArgs:+ words = parse_words(rest, escape_token)+ if not words:+ return [], False++ # Old format: KEY name value+ if "=" not in words[0]:+ match = _WHITESPACE.search(rest)+ if not match:+ raise ValueError(f"{key} must have two arguments")+ return [rest[: match.start()], rest[match.end() :], ""], False++ args: List[str] = []+ for word in words:+ if "=" not in word:+ raise ValueError(+ f'Syntax error - can\'t find = in "{word}". Must be of the form: name=value'+ )+ name, value = word.split("=", 1)+ args.extend([name, value, "="])+ return args, False++ return parse+++_LINE_PARSERS: Dict[str, LineParser] = {+ "ADD": _parse_maybe_json_to_words,+ "ARG": _parse_name_or_name_val,+ "CMD": _parse_maybe_json,+ "COPY": _parse_maybe_json_to_words,+ "ENTRYPOINT": _parse_maybe_json,+ "ENV": _parse_name_val("ENV"),+ "EXPOSE": _parse_strings_whitespace_delimited,+ "FROM": _parse_strings_whitespace_delimited,+ "HEALTHCHECK": _parse_health_config,+ "LABEL": _parse_name_val("LABEL"),+ "MAINTAINER": _parse_string,+ "ONBUILD": _parse_ignore,+ "RUN": _parse_maybe_json,+ "SHELL": _parse_maybe_json,+ "STOPSIGNAL": _parse_string,+ "USER": _parse_string,+ "VOLUME": _parse_maybe_json_to_list,+ "WORKDIR": _parse_string,+}+++def _extract_builder_flags(line: str, escape_token: str) -> Tuple[str, List[str]]:+ """Parses leading ``--flag[=value]`` words. Returns the remaining line and flags."""+ flags: List[str] = []+ phase = "spaces"+ quote = ""+ blank_ok = False+ word: List[str] = []+ length = len(line)+ pos = 0++ while pos <= length:+ ch = line[pos] if pos < length else ""++ if phase == "spaces":+ if pos == length:+ break+ if is_space(ch):+ pos += 1+ continue+ # only keep going if the next word starts with --+ if ch != "-" or pos + 1 == length or line[pos + 1] != "-":+ return line[pos:], flags+ phase = "word"+ if pos == length:+ joined = "".join(word)+ if joined != "--" and (blank_ok or word):+ flags.append(joined)+ break+ if phase == "word":+ if is_space(ch):+ phase = "spaces"+ joined = "".join(word)+ if joined == "--":+ return line[pos:], flags+ if blank_ok or word:+ flags.append(joined)+ word = []+ blank_ok = False+ pos += 1+ continue+ if ch in ("'", '"'):+ quote = ch+ blank_ok = True+ phase = "quote"+ pos += 1+ continue+ if ch == escape_token:+ if pos + 1 == length:+ pos += 1+ continue+ pos += 1+ word.append(line[pos])+ pos += 1+ continue+ word.append(ch)+ pos += 1+ continue+ # phase == "quote"+ if ch == quote:+ phase = "word"+ pos += 1+ continue+ if ch == escape_token:+ if pos + 1 == length:+ phase = "word"+ pos += 1+ continue+ pos += 1+ word.append(line[pos])+ pos += 1+ continue+ word.append(ch)+ pos += 1++ return "", flags+++def _split_command(line: str, escape_token: str) -> Tuple[str, List[str], str]:+ trimmed = line.strip()+ match = _WHITESPACE.search(trimmed)+ if not match:+ return trimmed, [], ""+ command = trimmed[: match.start()]+ rest, flags = _extract_builder_flags(trimmed[match.end() :], escape_token)+ return command, flags, rest.strip()+++def _match_heredoc_marker(word: str) -> Optional[Tuple[str, bool, str]]:+ """Split ``[fd]<<[-]name`` into its parts without a backtracking regex."""+ i = 0+ while i < len(word) and word[i] in _ASCII_DIGITS:+ i += 1+ if not word.startswith("<<", i):+ return None+ file_descriptor = word[:i]+ i += 2+ chomp = i < len(word) and word[i] == "-"+ if chomp:+ i += 1+ while i < len(word) and word[i] in _ASCII_SPACES:+ i += 1+ rest = word[i:]+ if "<" in rest:+ return None+ return file_descriptor, chomp, rest+++def parse_heredoc(word: str) -> Optional[DockerfileHeredoc]:+ match = _match_heredoc_marker(word)+ if match is None:+ return None+ fd, chomp, rest = match+ file_descriptor = int(fd) if fd else 0+ if not rest:+ return None++ # Lex the terminator both with and without quotes. If the results+ # differ, part of the word was quoted and the content must not expand.+ words = ShellLex("\\").process_words(rest)+ if len(words) != 1:+ return None+ words_raw = ShellLex("\\", raw_quotes=True).process_words(rest)+ if len(words_raw) != len(words):+ raise ValueError(+ f"internal lexing of heredoc produced inconsistent results: {rest}"+ )++ def count_quotes(s: str) -> int:+ return s.count("'") + s.count('"')++ expand = count_quotes(words[0]) == count_quotes(words_raw[0])+ return DockerfileHeredoc(+ name=words[0],+ content="",+ chomp=chomp,+ expand=expand,+ file_descriptor=file_descriptor,+ )+++def _heredocs_from_line(line: str) -> List[DockerfileHeredoc]:+ try:+ words = ShellLex("\\", raw_quotes=True, raw_escapes=True).process_words(line)+ except ValueError:+ return []+ heredocs: List[DockerfileHeredoc] = []+ for word in words:+ heredoc = parse_heredoc(word)+ if heredoc is not None:+ heredocs.append(heredoc)+ return heredocs+++def chomp_heredoc_content(content: str) -> str:+ """Strips leading tabs from every line (``<<-`` heredocs)."""+ return re.sub(r"^\t+", "", content, flags=re.MULTILINE)+++def parse_dockerfile_ast(content: str) -> DockerfileAst:+ directives = _Directives()+ if content.startswith("\ufeff"):+ content = content[1:]+ lines = _split_lines(content)+ instructions: List[DockerfileInstruction] = []+ warnings: List[DockerfileWarning] = []++ current_line = 0+ index = 0++ def process_line(raw: str, strip_left_whitespace: bool) -> str:+ line = _trim_newline(raw)+ if strip_left_whitespace:+ line = _trim_leading_whitespace(line)+ try:+ directives.possible_parser_directive(line)+ except ValueError as err:+ raise DockerfileSyntaxError(str(err), current_line + 1) from None+ return "" if _is_comment(line) else line++ while index < len(lines):+ raw = lines[index]+ index += 1+ line = process_line(raw, True)+ current_line += 1+ start_line = current_line++ line, is_end_of_line = directives.trim_continuation(line)+ if is_end_of_line and not line:+ continue++ has_empty_continuation_line = False+ while not is_end_of_line and index < len(lines):+ continuation_raw = lines[index]+ index += 1+ continuation = process_line(continuation_raw, False)+ current_line += 1++ if _is_comment(continuation_raw):+ continue+ if not _trim_leading_whitespace(_trim_newline(continuation_raw)):+ has_empty_continuation_line = True+ continue++ trimmed, is_end_of_line = directives.trim_continuation(continuation)+ line += trimmed++ if has_empty_continuation_line:+ warnings.append(+ DockerfileWarning(+ message=f"Empty continuation line found in: {line}",+ line=current_line,+ )+ )++ command, flags, rest = _split_command(line, directives.escape_token)+ name = command.upper()+ line_parser = _LINE_PARSERS.get(name)+ if line_parser is None:+ raise DockerfileSyntaxError(f"unknown instruction: {command}", start_line)++ try:+ args, is_json = line_parser(rest, directives.escape_token)+ except DockerfileSyntaxError:+ raise+ except ValueError as err:+ raise DockerfileSyntaxError(str(err), start_line) from None++ instruction = DockerfileInstruction(+ name=name,+ original=line,+ flags=flags,+ args=args,+ json=is_json,+ heredocs=[],+ start_line=start_line,+ end_line=current_line,+ )++ if name in _HEREDOC_INSTRUCTIONS and not is_json and "<<" in line:+ try:+ heredocs = _heredocs_from_line(line)+ except ValueError as err:+ raise DockerfileSyntaxError(str(err), start_line) from None+ for heredoc in heredocs:+ terminated = False+ content_lines: List[str] = []+ while index < len(lines):+ heredoc_line = lines[index]+ index += 1+ current_line += 1++ possible_terminator = _trim_newline(heredoc_line)+ if heredoc.chomp:+ possible_terminator = possible_terminator.lstrip("\t")+ if possible_terminator == heredoc.name:+ terminated = True+ break+ content_lines.append(heredoc_line)+ if not terminated:+ raise DockerfileSyntaxError("unterminated heredoc", start_line)+ heredoc.content = "".join(content_lines)+ instruction.heredocs.append(heredoc)+ instruction.end_line = current_line++ instructions.append(instruction)++ return DockerfileAst(+ instructions=instructions,+ escape_token=directives.escape_token,+ warnings=warnings,+ )diff --git a/packages/dockerfile-utils-python/package.json b/packages/dockerfile-utils-python/package.jsonnew file mode 100644index 000000000..dd31eb040--- /dev/null+++ b/packages/dockerfile-utils-python/package.json@@ -0,0 +1,14 @@+{+ "name": "@e2b/dockerfile-utils-python",+ "private": true,+ "version": "0.0.0",+ "scripts": {+ "test": "uv run pytest --verbose",+ "postVersion": "uv version --frozen $(pnpm pkg get version --workspaces=false | tr -d \\\")",+ "lock": "uv lock",+ "postPublish": "uv build && uv publish --trusted-publishing always --check-url https://pypi.org/simple/",+ "typecheck": "uv run make typecheck",+ "lint": "uv run make lint",+ "format": "uv run make format"+ }+}diff --git a/packages/dockerfile-utils-python/pyproject.toml b/packages/dockerfile-utils-python/pyproject.tomlnew file mode 100644index 000000000..16a753271--- /dev/null+++ b/packages/dockerfile-utils-python/pyproject.toml@@ -0,0 +1,30 @@+[project]+name = "e2b-dockerfile-utils"+version = "0.0.0"+description = "E2B Dockerfile utils - Dockerfile parser, shell lexer and .dockerignore matcher ported from BuildKit and Moby"+authors = [{ name = "e2b", email = "[email protected]" }]+license = "Apache-2.0"+license-files = ["LICENSE", "NOTICE"]+readme = "README.md"+requires-python = ">=3.10"+dependencies = []++[project.urls]+Homepage = "https://e2b.dev/?utm_source=pypi&utm_medium=referral&utm_campaign=package_homepage&utm_content=e2b-dockerfile-utils"+Repository = "https://github.com/e2b-dev/e2b/tree/main/packages/dockerfile-utils-python"+"Bug Tracker" = "https://github.com/e2b-dev/e2b/issues"++[dependency-groups]+dev = [+ "pytest>=9.0.3,<10",+ "ruff>=0.11.12,<0.12",+ "ty>=0.0.15,<0.0.16",+]++[build-system]+requires = ["uv_build>=0.10.0,<0.11.0"]+build-backend = "uv_build"++[tool.uv.build-backend]+module-name = ["e2b_dockerfile_utils"]+module-root = ""diff --git a/packages/dockerfile-utils-python/pytest.ini b/packages/dockerfile-utils-python/pytest.ininew file mode 100644index 000000000..f8dffe0fd--- /dev/null+++ b/packages/dockerfile-utils-python/pytest.ini@@ -0,0 +1,2 @@+[pytest]+addopts = "--import-mode=importlib"diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/README.md b/packages/dockerfile-utils-python/tests/fixtures/buildkit/README.mdnew file mode 100644index 000000000..1f267ca03--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/README.md@@ -0,0 +1,37 @@+# BuildKit test fixtures++Test data from [moby/buildkit](https://github.com/moby/buildkit) v0.26.1+(`frontend/dockerfile`, Apache License 2.0).++- `parser/`: verbatim copies of `parser/testfiles`, `parser/testfiles-negative`+ and `parser/testfile-line`. Each `result` is the `Node.Dump()` output of the+ upstream parser.+- `shell/envVarTest.env.json`: the Unix/All lines of `shell/envVarTest` with+ the upstream expectations verbatim (`TestShellParser4EnvVars`: the+ environment is `PWD=/home SHELL=bash KOREAN=한국어 NULL=`, unset variables+ expand to an empty string).+- `shell/wordsTest.env.json`: the lines of `shell/wordsTest` with the `ENV`+ lines applied cumulatively, upstream expectations verbatim+ (`TestShellParser4Words`, normal mode; unset variables expand to an empty+ string).+- `shell/processWithMatches.json`: the `TestProcessWithMatches` table from+ `shell/lex_test.go` (input, environment, expected word or error).+- `shell/`: the inputs of `shell/wordsTest` and `shell/envVarTest` with+ expectations generated by the upstream lexer in its variable-preserving+ mode (BuildKit's `SkipUnsetEnv` with an empty environment), which is how+ this lexer behaves without an `env`:++ ```go+ lex := shell.NewLex('\\')+ lex.SkipUnsetEnv = true+ lex.RawQuotes = rawQuotes // wordsTest.rawQuotes.json+ env := shell.EnvsFromSlice(nil)+ word, _, err := lex.ProcessWord(input, env)+ words, err := lex.ProcessWords(input, env)+ ```++ `ProcessWords` upstream loses the text before a `${VAR<modifier>...}`+ expression (`he${XXX:-000}xx` → `${XXX:-000}xx`): the nested+ `processStopOn` call for the modifier resets the shared words buffer. The+ `words` of those `envVarTest.json` entries are the intact words, the+ upstream output is kept as `buildkitWords`.diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfile-line/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfile-line/Dockerfilenew file mode 100644index 000000000..39184011a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfile-line/Dockerfile@@ -0,0 +1,35 @@+# ESCAPE=\++++FROM brimstone/ubuntu:14.04+++# TORUN -v /var/run/docker.sock:/var/run/docker.sock+++ENV GOPATH \+/go++++# Install the packages we need, clean up after them and us+RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+++ && apt-get --no-install-recommends install -y git golang ca-certificates \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/brimstone/consuldock \+ && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATH++++diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/empty_dockerfile/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/empty_dockerfile/Dockerfilenew file mode 100644index 000000000..e69de29bbdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfilenew file mode 100644index 000000000..1d6557879--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/env_no_value/Dockerfile@@ -0,0 +1,3 @@+FROM busybox++ENV PATHdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfilenew file mode 100644index 000000000..5dd027a67--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/only_comments/Dockerfile@@ -0,0 +1,3 @@+# Hello+# These are just comments+diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfilenew file mode 100644index 000000000..d1be4596c--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles-negative/shykes-nested-json/Dockerfile@@ -0,0 +1 @@+CMD [ "echo", [ "nested json" ] ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfilenew file mode 100644index 000000000..035b4e8bb--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/Dockerfile@@ -0,0 +1,11 @@+FROM ubuntu:14.04+LABEL maintainer Seongyeol Lim <[email protected]>++COPY . /go/src/github.com/docker/docker+ADD . /+ADD null /+COPY nullfile /tmp+ADD [ "vimrc", "/tmp" ]+COPY [ "bashrc", "/tmp" ]+COPY [ "test file", "/tmp" ]+ADD [ "test file", "/tmp/test file" ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/resultnew file mode 100644index 000000000..8468693dc--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/ADD-COPY-with-JSON/result@@ -0,0 +1,10 @@+(from "ubuntu:14.04")+(label "maintainer" "Seongyeol Lim <[email protected]>" "")+(copy "." "/go/src/github.com/docker/docker")+(add "." "/")+(add "null" "/")+(copy "nullfile" "/tmp")+(add "vimrc" "/tmp")+(copy "bashrc" "/tmp")+(copy "test file" "/tmp")+(add "test file" "/tmp/test file")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/Dockerfilenew file mode 100644index 000000000..6dcbdb9c2--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/Dockerfile@@ -0,0 +1,3 @@+ARG foo bar=baz+FROM ubuntu+ARG abc="123 456" defdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/resultnew file mode 100644index 000000000..90db1d5b8--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/args/result@@ -0,0 +1,3 @@+(arg "foo" "bar=baz")+(from "ubuntu")+(arg "abc=\"123 456\"" "def")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfilenew file mode 100644index 000000000..67c67f723--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/Dockerfile@@ -0,0 +1,26 @@+#escape=\+FROM brimstone/ubuntu:14.04++LABEL maintainer [email protected]++# TORUN -v /var/run/docker.sock:/var/run/docker.sock++ENV GOPATH /go++# Set our command+ENTRYPOINT ["/usr/local/bin/consuldock"]++# Install the packages we need, clean up after them and us+RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y git golang ca-certificates \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/brimstone/consuldock \+ && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATHdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/resultnew file mode 100644index 000000000..3749f7c7e--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-consuldock/result@@ -0,0 +1,5 @@+(from "brimstone/ubuntu:14.04")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "/go" "")+(entrypoint "/usr/local/bin/consuldock")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y git golang ca-certificates && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/brimstone/consuldock && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfilenew file mode 100644index 000000000..95c3dec9a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/Dockerfile@@ -0,0 +1,52 @@+FROM brimstone/ubuntu:14.04++CMD []++ENTRYPOINT ["/usr/bin/consul", "agent", "-server", "-data-dir=/consul", "-client=0.0.0.0", "-ui-dir=/webui"]++EXPOSE 8500 8600 8400 8301 8302++RUN apt-get update \+ && apt-get --no-install-recommends install -y unzip wget \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists++RUN cd /tmp \+ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \+ -O web_ui.zip \+ && unzip web_ui.zip \+ && mv dist /webui \+ && rm web_ui.zip++RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y unzip wget \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && cd /tmp \+ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \+ -O web_ui.zip \+ && unzip web_ui.zip \+ && mv dist /webui \+ && rm web_ui.zip \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.*++ENV GOPATH /go++RUN apt-get update \+ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \+ && apt-get --no-install-recommends install -y git golang ca-certificates build-essential \+ && apt-get clean \+ && rm -rf /var/lib/apt/lists \++ && go get -v github.com/hashicorp/consul \+ && mv $GOPATH/bin/consul /usr/bin/consul \++ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \+ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \+ && rm /tmp/dpkg.* \+ && rm -rf $GOPATHdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/resultnew file mode 100644index 000000000..168c8d61c--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/brimstone-docker-consul/result@@ -0,0 +1,9 @@+(from "brimstone/ubuntu:14.04")+(cmd)+(entrypoint "/usr/bin/consul" "agent" "-server" "-data-dir=/consul" "-client=0.0.0.0" "-ui-dir=/webui")+(expose "8500" "8600" "8400" "8301" "8302")+(run "apt-get update && apt-get --no-install-recommends install -y unzip wget \t&& apt-get clean \t&& rm -rf /var/lib/apt/lists")+(run "cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y unzip wget && apt-get clean && rm -rf /var/lib/apt/lists && cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.*")+(env "GOPATH" "/go" "")+(run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get --no-install-recommends install -y git golang ca-certificates build-essential && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/hashicorp/consul \t&& mv $GOPATH/bin/consul /usr/bin/consul \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfilenew file mode 100644index 000000000..a8ec369ad--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/Dockerfile@@ -0,0 +1,3 @@+FROM alpine:3.5++RUN something \\ No newline at end of filediff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/resultnew file mode 100644index 000000000..14e4f0932--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continue-at-eof/result@@ -0,0 +1,2 @@+(from "alpine:3.5")+(run "something")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfilenew file mode 100644index 000000000..42b324e77--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/Dockerfile@@ -0,0 +1,36 @@+FROM ubuntu:14.04++RUN echo hello\+ world\+ goodnight \+ moon\+ light\+ning+RUN echo hello \+ world+RUN echo hello \+world+RUN echo hello \+goodbye\+frog+RUN echo hello \+world+RUN echo hi \+ \+ world \+\+ good\+\+night+RUN echo goodbye\+frog+RUN echo good\+bye\+frog++RUN echo hello \+# this is a comment++# this is a comment with a blank line surrounding it++this is some more useful stuffdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/resultnew file mode 100644index 000000000..268ae073c--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/continueIndent/result@@ -0,0 +1,10 @@+(from "ubuntu:14.04")+(run "echo hello world goodnight moon lightning")+(run "echo hello world")+(run "echo hello world")+(run "echo hello goodbyefrog")+(run "echo hello world")+(run "echo hi world goodnight")+(run "echo goodbyefrog")+(run "echo goodbyefrog")+(run "echo hello this is some more useful stuff")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfilenew file mode 100644index 000000000..b10e67a7e--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/Dockerfile@@ -0,0 +1,54 @@+FROM cpuguy83/ubuntu+ENV NAGIOS_HOME /opt/nagios+ENV NAGIOS_USER nagios+ENV NAGIOS_GROUP nagios+ENV NAGIOS_CMDUSER nagios+ENV NAGIOS_CMDGROUP nagios+ENV NAGIOSADMIN_USER nagiosadmin+ENV NAGIOSADMIN_PASS nagios+ENV APACHE_RUN_USER nagios+ENV APACHE_RUN_GROUP nagios+ENV NAGIOS_TIMEZONE UTC++RUN sed -i 's/universe/universe multiverse/' /etc/apt/sources.list+RUN apt-get update && apt-get --no-install-recommends install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx+RUN ( egrep -i "^${NAGIOS_GROUP}" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i "^${NAGIOS_CMDGROUP}" /etc/group || groupadd $NAGIOS_CMDGROUP )+RUN ( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER )++ADD http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3 /tmp/nagios.tar.gz+RUN cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf+ADD http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz /tmp/+RUN cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install++RUN sed -i.bak 's/.*\=www\-data//g' /etc/apache2/envvars+RUN export DOC_ROOT="DocumentRoot $(echo $NAGIOS_HOME/share)"; sed -i "s,DocumentRoot.*,$DOC_ROOT," /etc/apache2/sites-enabled/000-default++RUN ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo++RUN echo "use_timezone=$NAGIOS_TIMEZONE" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo "SetEnv TZ \"${NAGIOS_TIMEZONE}\"" >> /etc/apache2/conf.d/nagios.conf++RUN mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs+RUN echo "cfg_dir=${NAGIOS_HOME}/etc/conf.d" >> ${NAGIOS_HOME}/etc/nagios.cfg+RUN echo "cfg_dir=${NAGIOS_HOME}/etc/monitor" >> ${NAGIOS_HOME}/etc/nagios.cfg+RUN download-mibs && echo "mibs +ALL" > /etc/snmp/snmp.conf++RUN sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && \+ sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg+RUN cp /etc/services /var/spool/postfix/etc/++RUN mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix+ADD nagios.init /etc/sv/nagios/run+ADD apache.init /etc/sv/apache/run+ADD postfix.init /etc/sv/postfix/run+ADD postfix.stop /etc/sv/postfix/finish++ADD start.sh /usr/local/bin/start_nagios++ENV APACHE_LOCK_DIR /var/run+ENV APACHE_LOG_DIR /var/log/apache2++EXPOSE 80++VOLUME ["/opt/nagios/var", "/opt/nagios/etc", "/opt/nagios/libexec", "/var/log/apache2", "/usr/share/snmp/mibs"]++CMD ["/usr/local/bin/start_nagios"]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/resultnew file mode 100644index 000000000..f009ac681--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/cpuguy83-nagios/result@@ -0,0 +1,40 @@+(from "cpuguy83/ubuntu")+(env "NAGIOS_HOME" "/opt/nagios" "")+(env "NAGIOS_USER" "nagios" "")+(env "NAGIOS_GROUP" "nagios" "")+(env "NAGIOS_CMDUSER" "nagios" "")+(env "NAGIOS_CMDGROUP" "nagios" "")+(env "NAGIOSADMIN_USER" "nagiosadmin" "")+(env "NAGIOSADMIN_PASS" "nagios" "")+(env "APACHE_RUN_USER" "nagios" "")+(env "APACHE_RUN_GROUP" "nagios" "")+(env "NAGIOS_TIMEZONE" "UTC" "")+(run "sed -i 's/universe/universe multiverse/' /etc/apt/sources.list")+(run "apt-get update && apt-get --no-install-recommends install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx")+(run "( egrep -i \"^${NAGIOS_GROUP}\" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i \"^${NAGIOS_CMDGROUP}\" /etc/group || groupadd $NAGIOS_CMDGROUP )")+(run "( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER )")+(add "http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3" "/tmp/nagios.tar.gz")+(run "cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf")+(add "http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz" "/tmp/")+(run "cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install")+(run "sed -i.bak 's/.*\\=www\\-data//g' /etc/apache2/envvars")+(run "export DOC_ROOT=\"DocumentRoot $(echo $NAGIOS_HOME/share)\"; sed -i \"s,DocumentRoot.*,$DOC_ROOT,\" /etc/apache2/sites-enabled/000-default")+(run "ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo")+(run "echo \"use_timezone=$NAGIOS_TIMEZONE\" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo \"SetEnv TZ \\\"${NAGIOS_TIMEZONE}\\\"\" >> /etc/apache2/conf.d/nagios.conf")+(run "mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs")+(run "echo \"cfg_dir=${NAGIOS_HOME}/etc/conf.d\" >> ${NAGIOS_HOME}/etc/nagios.cfg")+(run "echo \"cfg_dir=${NAGIOS_HOME}/etc/monitor\" >> ${NAGIOS_HOME}/etc/nagios.cfg")+(run "download-mibs && echo \"mibs +ALL\" > /etc/snmp/snmp.conf")+(run "sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg")+(run "cp /etc/services /var/spool/postfix/etc/")+(run "mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix")+(add "nagios.init" "/etc/sv/nagios/run")+(add "apache.init" "/etc/sv/apache/run")+(add "postfix.init" "/etc/sv/postfix/run")+(add "postfix.stop" "/etc/sv/postfix/finish")+(add "start.sh" "/usr/local/bin/start_nagios")+(env "APACHE_LOCK_DIR" "/var/run" "")+(env "APACHE_LOG_DIR" "/var/log/apache2" "")+(expose "80")+(volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs")+(cmd "/usr/local/bin/start_nagios")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfilenew file mode 100644index 000000000..9010bbc83--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/Dockerfile@@ -0,0 +1,94 @@+# This file describes the standard way to build Docker, using docker+#+# Usage:+#+# # Assemble the full dev environment. This is slow the first time.+# docker build -t docker .+#+# # Mount your source in an interactive container for quick testing:+# docker run -v `pwd`:/go/src/github.com/docker/docker --privileged -i -t docker bash+#+# # Run the test suite:+# docker run --privileged docker hack/make.sh test-unit test-integration test-docker-py+#+# Note: AppArmor used to mess with privileged mode, but this is no longer+# the case. Therefore, you don't have to disable it anymore.+#++FROM ubuntu:14.04+LABEL maintainer Tianon Gravi <[email protected]> (@tianon)++# Packaged dependencies+RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -yq \+ apt-utils \+ aufs-tools \+ automake \+ btrfs-tools \+ build-essential \+ curl \+ dpkg-sig \+ git \+ iptables \+ libapparmor-dev \+ libcap-dev \+ mercurial \+ pandoc \+ parallel \+ reprepro \+ ruby1.9.1 \+ ruby1.9.1-dev \+ s3cmd=1.1.0* \+ --no-install-recommends++# Get lvm2 source for compiling statically+RUN git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103+# see https://git.fedorahosted.org/cgit/lvm2.git/refs/tags for release tags+# note: we don't use "git clone -b" above because it then spews big nasty warnings about 'detached HEAD' state that we can't silence as easily as we can silence them using "git checkout" directly++# Compile and install lvm2+RUN cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper+# see https://git.fedorahosted.org/cgit/lvm2.git/tree/INSTALL++# Install Go+RUN curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz+ENV PATH /usr/local/go/bin:$PATH+ENV GOPATH /go:/go/src/github.com/docker/docker/vendor+RUN cd /usr/local/go/src && ./make.bash --no-clean 2>&1++# Compile Go for cross compilation+ENV DOCKER_CROSSPLATFORMS \+ linux/386 linux/arm \+ darwin/amd64 darwin/386 \+ freebsd/amd64 freebsd/386 freebsd/arm+# (set an explicit GOARM of 5 for maximum compatibility)+ENV GOARM 5+RUN cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done'++# Grab Go's cover tool for dead-simple code coverage testing+RUN go get golang.org/x/tools/cmd/cover++# TODO replace FPM with some very minimal debhelper stuff+RUN gem install --no-rdoc --no-ri fpm --version 1.0.2++# Get the "busybox" image source so we can build locally instead of pulling+RUN git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox++# Setup s3cmd config+RUN /bin/echo -e '[default]\naccess_key=$AWS_ACCESS_KEY\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg++# Set user.email so crosbymichael's in-container merge commits go smoothly+RUN git config --global user.email '[email protected]'++# Add an unprivileged user to be used for tests which need it+RUN groupadd -r docker+RUN useradd --create-home --gid docker unprivilegeduser++VOLUME /var/lib/docker+WORKDIR /go/src/github.com/docker/docker+ENV DOCKER_BUILDTAGS apparmor selinux++# Wrap all commands in the "docker-in-docker" script to allow nested containers+ENTRYPOINT ["hack/dind"]++# Upload docker source+COPY . /go/src/github.com/docker/dockerdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/resultnew file mode 100644index 000000000..fa558cd5e--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/docker/result@@ -0,0 +1,24 @@+(from "ubuntu:14.04")+(label "maintainer" "Tianon Gravi <[email protected]> (@tianon)" "")+(run "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -yq \tapt-utils \taufs-tools \tautomake \tbtrfs-tools \tbuild-essential \tcurl \tdpkg-sig \tgit \tiptables \tlibapparmor-dev \tlibcap-dev \tmercurial \tpandoc \tparallel \treprepro \truby1.9.1 \truby1.9.1-dev \ts3cmd=1.1.0* \t--no-install-recommends")+(run "git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103")+(run "cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper")+(run "curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz")+(env "PATH" "/usr/local/go/bin:$PATH" "")+(env "GOPATH" "/go:/go/src/github.com/docker/docker/vendor" "")+(run "cd /usr/local/go/src && ./make.bash --no-clean 2>&1")+(env "DOCKER_CROSSPLATFORMS" "linux/386 linux/arm \tdarwin/amd64 darwin/386 \tfreebsd/amd64 freebsd/386 freebsd/arm" "")+(env "GOARM" "5" "")+(run "cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done'")+(run "go get golang.org/x/tools/cmd/cover")+(run "gem install --no-rdoc --no-ri fpm --version 1.0.2")+(run "git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox")+(run "/bin/echo -e '[default]\\naccess_key=$AWS_ACCESS_KEY\\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg")+(run "git config --global user.email '[email protected]'")+(run "groupadd -r docker")+(run "useradd --create-home --gid docker unprivilegeduser")+(volume "/var/lib/docker")+(workdir "/go/src/github.com/docker/docker")+(env "DOCKER_BUILDTAGS" "apparmor selinux" "")+(entrypoint "hack/dind")+(copy "." "/go/src/github.com/docker/docker")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/Dockerfilenew file mode 100644index 000000000..08fa18ace--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/Dockerfile@@ -0,0 +1,23 @@+FROM ubuntu+ENV name value+ENV name=value+ENV name=value name2=value2+ENV name="value value1"+ENV name=value\ value2+ENV name="value'quote space'value2"+ENV name='value"double quote"value2'+ENV name=value\ value2 name2=value2\ value3+ENV name="a\"b"+ENV name="a\'b"+ENV name='a\'b'+ENV name='a\'b''+ENV name='a\"b'+ENV name="''"+# don't put anything after the next line - it must be the last line of the+# Dockerfile and it must end with \+ENV name=value \+ name1=value1 \+ name2="value2a \+ value2b" \+ name3="value3a\n\"value3b\"" \+ name4="value4a\\nvalue4b" \diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/resultnew file mode 100644index 000000000..2d56c78bd--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/env/result@@ -0,0 +1,16 @@+(from "ubuntu")+(env "name" "value" "")+(env "name" "value" "=")+(env "name" "value" "=" "name2" "value2" "=")+(env "name" "\"value value1\"" "=")+(env "name" "value\\ value2" "=")+(env "name" "\"value'quote space'value2\"" "=")+(env "name" "'value\"double quote\"value2'" "=")+(env "name" "value\\ value2" "=" "name2" "value2\\ value3" "=")+(env "name" "\"a\\\"b\"" "=")+(env "name" "\"a\\'b\"" "=")+(env "name" "'a\\'b'" "=")+(env "name" "'a\\'b''" "=")+(env "name" "'a\\\"b'" "=")+(env "name" "\"''\"" "=")+(env "name" "value" "=" "name1" "value1" "=" "name2" "\"value2a value2b\"" "=" "name3" "\"value3a\\n\\\"value3b\\\"\"" "=" "name4" "\"value4a\\\\nvalue4b\"" "=")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfilenew file mode 100644index 000000000..18e9a474f--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/Dockerfile@@ -0,0 +1,9 @@+# Comment here. Should not be looking for the following parser directive.+# Hence the following line will be ignored, and the subsequent backslash+# continuation will be the default.+# escape = `++FROM image+LABEL maintainer [email protected]+ENV GOPATH \+\go\ No newline at end of filediff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-after-comment/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfilenew file mode 100644index 000000000..bbe94a3eb--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/Dockerfile@@ -0,0 +1,7 @@+# escape = `+# There is no white space line after the directives. This still succeeds, but goes+# against best practices.+FROM image+LABEL maintainer [email protected]+ENV GOPATH `+\godiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-nonewline/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfilenew file mode 100644index 000000000..527a5c14e--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/Dockerfile@@ -0,0 +1,5 @@+# syntax = docker/dockerfile+# escape = `++FROM `+ imagediff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/resultnew file mode 100644index 000000000..62e9e267d--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape-with-syntax/result@@ -0,0 +1 @@+(from "image")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfilenew file mode 100644index 000000000..a515af152--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/Dockerfile@@ -0,0 +1,6 @@+#escape = `++FROM image+LABEL maintainer [email protected]+ENV GOPATH `+\go\ No newline at end of filediff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/resultnew file mode 100644index 000000000..c6c87f053--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escape/result@@ -0,0 +1,3 @@+(from "image")+(label "maintainer" "[email protected]" "")+(env "GOPATH" "\\go" "")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfilenew file mode 100644index 000000000..03062394a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/Dockerfile@@ -0,0 +1,14 @@+FROM ubuntu:14.04+LABEL maintainer Erik \\Hollensbe <[email protected]>\"++RUN apt-get \update && \+ apt-get \"install znc -y+ADD \conf\\" /.znc++RUN foo \++bar \++baz++CMD [ "\/usr\\\"/bin/znc", "-f", "-r" ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/resultnew file mode 100644index 000000000..29579f439--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/escapes/result@@ -0,0 +1,6 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik \\\\Hollensbe <[email protected]>\\\"" "")+(run "apt-get \\update && apt-get \\\"install znc -y")+(add "\\conf\\\\\"" "/.znc")+(run "foo bar baz")+(cmd "/usr\\\"/bin/znc" "-f" "-r")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfilenew file mode 100644index 000000000..2418e0f06--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/Dockerfile@@ -0,0 +1,10 @@+FROM scratch+COPY foo /tmp/+COPY --user=me foo /tmp/+COPY --doit=true foo /tmp/+COPY --user=me --doit=true foo /tmp/+COPY --doit=true -- foo /tmp/+COPY -- foo /tmp/+CMD --doit [ "a", "b" ]+CMD --doit=true -- [ "a", "b" ]+CMD --doit -- [ ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/resultnew file mode 100644index 000000000..4578f4cba--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/flags/result@@ -0,0 +1,10 @@+(from "scratch")+(copy "foo" "/tmp/")+(copy ["--user=me"] "foo" "/tmp/")+(copy ["--doit=true"] "foo" "/tmp/")+(copy ["--user=me" "--doit=true"] "foo" "/tmp/")+(copy ["--doit=true"] "foo" "/tmp/")+(copy "foo" "/tmp/")+(cmd ["--doit"] "a" "b")+(cmd ["--doit=true"] "a" "b")+(cmd ["--doit"])diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/Dockerfilenew file mode 100644index 000000000..0e6f97e73--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/Dockerfile@@ -0,0 +1,11 @@+FROM debian+ADD check.sh main.sh /app/+CMD /app/main.sh+HEALTHCHECK+HEALTHCHECK --interval=5s --timeout=3s --retries=3 \+ CMD /app/check.sh --quiet+HEALTHCHECK CMD+HEALTHCHECK CMD a b+HEALTHCHECK --timeout=3s CMD ["foo"]+HEALTHCHECK CONNECT TCP 7000+HEALTHCHECK --start-period=0s --start-interval=0s --interval=5s --timeout=0s --retries=0 CMD ["foo"]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/resultnew file mode 100644index 000000000..dc2c8a508--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/health/result@@ -0,0 +1,10 @@+(from "debian")+(add "check.sh" "main.sh" "/app/")+(cmd "/app/main.sh")+(healthcheck)+(healthcheck ["--interval=5s" "--timeout=3s" "--retries=3"] "CMD" "/app/check.sh --quiet")+(healthcheck "CMD")+(healthcheck "CMD" "a b")+(healthcheck ["--timeout=3s"] "CMD" "foo")+(healthcheck "CONNECT" "TCP 7000")+(healthcheck ["--start-period=0s" "--start-interval=0s" "--interval=5s" "--timeout=0s" "--retries=0"] "CMD" "foo")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfilenew file mode 100644index 000000000..587fb9b54--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/Dockerfile@@ -0,0 +1,15 @@+FROM ubuntu:14.04++RUN apt-get update && apt-get install wget -y+RUN wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb+RUN dpkg -i influxdb_latest_amd64.deb+RUN rm -r /opt/influxdb/shared++VOLUME /opt/influxdb/shared++CMD /usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml++EXPOSE 8083+EXPOSE 8086+EXPOSE 8090+EXPOSE 8099diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/resultnew file mode 100644index 000000000..0998e87e6--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/influxdb/result@@ -0,0 +1,11 @@+(from "ubuntu:14.04")+(run "apt-get update && apt-get install wget -y")+(run "wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb")+(run "dpkg -i influxdb_latest_amd64.deb")+(run "rm -r /opt/influxdb/shared")+(volume "/opt/influxdb/shared")+(cmd "/usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml")+(expose "8083")+(expose "8086")+(expose "8090")+(expose "8099")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfilenew file mode 100644index 000000000..39fe27d99--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfile@@ -0,0 +1 @@+CMD "[\"echo\", \"Phew, I just managed to escaped those double quotes\"]"diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/resultnew file mode 100644index 000000000..afc220c2a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string-double/result@@ -0,0 +1 @@+(cmd "\"[\\\"echo\\\", \\\"Phew, I just managed to escaped those double quotes\\\"]\"")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfilenew file mode 100644index 000000000..eaae081a0--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfile@@ -0,0 +1 @@+CMD '["echo", "Well, JSON in a string is JSON too?"]'diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/resultnew file mode 100644index 000000000..484804e2b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-json-inside-string/result@@ -0,0 +1 @@+(cmd "'[\"echo\", \"Well, JSON in a string is JSON too?\"]'")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfilenew file mode 100644index 000000000..c3ac63c07--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfile@@ -0,0 +1 @@+CMD ['echo','single quotes are invalid JSON']diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/resultnew file mode 100644index 000000000..614789120--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-single-quotes/result@@ -0,0 +1 @@+(cmd "['echo','single quotes are invalid JSON']")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfilenew file mode 100644index 000000000..5fd4afa52--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfile@@ -0,0 +1 @@+CMD ["echo", "Please, close the brackets when you're done"diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/resultnew file mode 100644index 000000000..1ffbb8ff8--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-bracket/result@@ -0,0 +1 @@+(cmd "[\"echo\", \"Please, close the brackets when you're done\"")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfilenew file mode 100644index 000000000..30cc4bb48--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfile@@ -0,0 +1 @@+CMD ["echo", "look ma, no quote!]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/resultnew file mode 100644index 000000000..32048147b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/jeztah-invalid-json-unterminated-string/result@@ -0,0 +1 @@+(cmd "[\"echo\", \"look ma, no quote!]")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/Dockerfilenew file mode 100644index 000000000..a58691711--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/Dockerfile@@ -0,0 +1,8 @@+CMD []+CMD [""]+CMD ["a"]+CMD ["a","b"]+CMD [ "a", "b" ]+CMD [ "a", "b" ]+CMD [ "a", "b" ]+CMD ["abc 123", "♥", "☃", "\" \\ \/ \b \f \n \r \t \u0000"]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/resultnew file mode 100644index 000000000..c6553e6e1--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/json/result@@ -0,0 +1,8 @@+(cmd)+(cmd "")+(cmd "a")+(cmd "a" "b")+(cmd "a" "b")+(cmd "a" "b")+(cmd "a" "b")+(cmd "abc 123" "♥" "☃" "\" \\ / \b \f \n \r \t \x00")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfilenew file mode 100644index 000000000..78317ace9--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04+LABEL maintainer James Turnbull "[email protected]"+ENV REFRESHED_AT 2014-06-01+RUN apt-get update+RUN apt-get --no-install-recommends install -y redis-server redis-tools+EXPOSE 6379+ENTRYPOINT [ "/usr/bin/redis-server" ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/resultnew file mode 100644index 000000000..3d175d152--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/kartar-entrypoint-oddities/result@@ -0,0 +1,7 @@+(from "ubuntu:14.04")+(label "maintainer" "James Turnbull \"[email protected]\"" "")+(env "REFRESHED_AT" "2014-06-01" "")+(run "apt-get update")+(run "apt-get --no-install-recommends install -y redis-server redis-tools")+(expose "6379")+(entrypoint "/usr/bin/redis-server")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfilenew file mode 100644index 000000000..27f28cb92--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfile@@ -0,0 +1,48 @@+FROM busybox:buildroot-2014.02++LABEL maintainer docker <[email protected]>++ONBUILD RUN ["echo", "test"]+ONBUILD RUN echo test+ONBUILD COPY . /+++# RUN Commands \+# linebreak in comment \+RUN ["ls", "-la"]+RUN ["echo", "'1234'"]+RUN echo "1234"+RUN echo 1234+RUN echo '1234' && \+ echo "456" && \+ echo 789+RUN sh -c 'echo root:testpass \+ > /tmp/passwd'+RUN mkdir -p /test /test2 /test3/test++# ENV \+ENV SCUBA 1 DUBA 3+ENV SCUBA "1 DUBA 3"++# CMD \+CMD ["echo", "test"]+CMD echo test+CMD echo "test"+CMD echo 'test'+CMD echo 'test' | wc -++#EXPOSE\+EXPOSE 3000+EXPOSE 9000 5000 6000++USER docker+USER docker:root++VOLUME ["/test"]+VOLUME ["/test", "/test2"]+VOLUME /test3++WORKDIR /test++ADD . /+COPY . copydiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/resultnew file mode 100644index 000000000..eee8872a6--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/lk4d4-the-edge-case-generator/result@@ -0,0 +1,29 @@+(from "busybox:buildroot-2014.02")+(label "maintainer" "docker <[email protected]>" "")+(onbuild (run "echo" "test"))+(onbuild (run "echo test"))+(onbuild (copy "." "/"))+(run "ls" "-la")+(run "echo" "'1234'")+(run "echo \"1234\"")+(run "echo 1234")+(run "echo '1234' && echo \"456\" && echo 789")+(run "sh -c 'echo root:testpass > /tmp/passwd'")+(run "mkdir -p /test /test2 /test3/test")+(env "SCUBA" "1 DUBA 3" "")+(env "SCUBA" "\"1 DUBA 3\"" "")+(cmd "echo" "test")+(cmd "echo test")+(cmd "echo \"test\"")+(cmd "echo 'test'")+(cmd "echo 'test' | wc -")+(expose "3000")+(expose "9000" "5000" "6000")+(user "docker")+(user "docker:root")+(volume "/test")+(volume "/test" "/test2")+(volume "/test3")+(workdir "/test")+(add "." "/")+(copy "." "copy")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfilenew file mode 100644index 000000000..f64c1168c--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/Dockerfile@@ -0,0 +1,16 @@+FROM ubuntu:14.04++RUN apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y+ADD .muttrc /+ADD .offlineimaprc /+ADD .tmux.conf /+ADD mutt /.mutt+ADD vim /.vim+ADD vimrc /.vimrc+ADD crontab /etc/crontab+RUN chmod 644 /etc/crontab+RUN mkdir /Mail+RUN mkdir /.offlineimap+RUN echo "export TERM=screen-256color" >/.zshenv++CMD setsid cron; tmux -2diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/resultnew file mode 100644index 000000000..a0efcf04b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mail/result@@ -0,0 +1,14 @@+(from "ubuntu:14.04")+(run "apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y")+(add ".muttrc" "/")+(add ".offlineimaprc" "/")+(add ".tmux.conf" "/")+(add "mutt" "/.mutt")+(add "vim" "/.vim")+(add "vimrc" "/.vimrc")+(add "crontab" "/etc/crontab")+(run "chmod 644 /etc/crontab")+(run "mkdir /Mail")+(run "mkdir /.offlineimap")+(run "echo \"export TERM=screen-256color\" >/.zshenv")+(cmd "setsid cron; tmux -2")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfilenew file mode 100644index 000000000..57bb5976a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/Dockerfile@@ -0,0 +1,3 @@+FROM foo++VOLUME /opt/nagios/var /opt/nagios/etc /opt/nagios/libexec /var/log/apache2 /usr/share/snmp/mibsdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/resultnew file mode 100644index 000000000..18dbdeeaa--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/multiple-volumes/result@@ -0,0 +1,2 @@+(from "foo")+(volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfilenew file mode 100644index 000000000..5b9ec06a6--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04++RUN apt-get update && apt-get install libcap2-bin mumble-server -y++ADD ./mumble-server.ini /etc/mumble-server.ini++CMD /usr/sbin/murmurddiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/resultnew file mode 100644index 000000000..a0036a943--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/mumble/result@@ -0,0 +1,4 @@+(from "ubuntu:14.04")+(run "apt-get update && apt-get install libcap2-bin mumble-server -y")+(add "./mumble-server.ini" "/etc/mumble-server.ini")+(cmd "/usr/sbin/murmurd")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfilenew file mode 100644index 000000000..0a35e2c6b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/Dockerfile@@ -0,0 +1,14 @@+FROM ubuntu:14.04+LABEL maintainer Erik Hollensbe <[email protected]>++RUN apt-get update && apt-get install nginx-full -y+RUN rm -rf /etc/nginx+ADD etc /etc/nginx+RUN chown -R root:root /etc/nginx+RUN /usr/sbin/nginx -qt+RUN mkdir /www++CMD ["/usr/sbin/nginx"]++VOLUME /www+EXPOSE 80diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/resultnew file mode 100644index 000000000..8382e6349--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/nginx/result@@ -0,0 +1,11 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik Hollensbe <[email protected]>" "")+(run "apt-get update && apt-get install nginx-full -y")+(run "rm -rf /etc/nginx")+(add "etc" "/etc/nginx")+(run "chown -R root:root /etc/nginx")+(run "/usr/sbin/nginx -qt")+(run "mkdir /www")+(cmd "/usr/sbin/nginx")+(volume "/www")+(expose "80")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfilenew file mode 100644index 000000000..72b79bdd7--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/Dockerfile@@ -0,0 +1,23 @@+FROM ubuntu:12.04++EXPOSE 27015+EXPOSE 27005+EXPOSE 26901+EXPOSE 27020++RUN apt-get update && apt-get install libc6-dev-i386 curl unzip -y+RUN mkdir -p /steam+RUN curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam+ADD ./script /steam/script+RUN /steam/steamcmd.sh +runscript /steam/script+RUN curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf+RUN curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf+ADD ./server.cfg /steam/tf2/tf/cfg/server.cfg+ADD ./ctf_2fort.cfg /steam/tf2/tf/cfg/ctf_2fort.cfg+ADD ./sourcemod.cfg /steam/tf2/tf/cfg/sourcemod/sourcemod.cfg+RUN rm -r /steam/tf2/tf/addons/sourcemod/configs+ADD ./configs /steam/tf2/tf/addons/sourcemod/configs+RUN mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en+RUN cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en++CMD cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode filldiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/resultnew file mode 100644index 000000000..d4f94cd8b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/tf2/result@@ -0,0 +1,20 @@+(from "ubuntu:12.04")+(expose "27015")+(expose "27005")+(expose "26901")+(expose "27020")+(run "apt-get update && apt-get install libc6-dev-i386 curl unzip -y")+(run "mkdir -p /steam")+(run "curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam")+(add "./script" "/steam/script")+(run "/steam/steamcmd.sh +runscript /steam/script")+(run "curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf")+(run "curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf")+(add "./server.cfg" "/steam/tf2/tf/cfg/server.cfg")+(add "./ctf_2fort.cfg" "/steam/tf2/tf/cfg/ctf_2fort.cfg")+(add "./sourcemod.cfg" "/steam/tf2/tf/cfg/sourcemod/sourcemod.cfg")+(run "rm -r /steam/tf2/tf/addons/sourcemod/configs")+(add "./configs" "/steam/tf2/tf/addons/sourcemod/configs")+(run "mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en")+(run "cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en")+(cmd "cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode fill")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfilenew file mode 100644index 000000000..90c651006--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/Dockerfile@@ -0,0 +1,17 @@+# https://github.com/docker/for-win/issues/5254++FROM hello-world++ENV A path+ENV B another\\path+ENV C trailing\\backslash\\+ENV D This should not be appended to C+ENV E hello\+\+world+ENV F hello\+ \+world+ENV G hello \+\+worlddiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/resultnew file mode 100644index 000000000..23a235c2c--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/trailing-backslash/result@@ -0,0 +1,8 @@+(from "hello-world")+(env "A" "path" "")+(env "B" "another\\\\path" "")+(env "C" "trailing\\\\backslash\\\\" "")+(env "D" "This should not be appended to C" "")+(env "E" "helloworld" "")+(env "F" "hello world" "")+(env "G" "hello world" "")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfilenew file mode 100644index 000000000..484208816--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/Dockerfile@@ -0,0 +1,9 @@+FROM ubuntu:14.04++RUN apt-get update -qy && apt-get install tmux zsh weechat-curses -y++ADD .weechat /.weechat+ADD .tmux.conf /+RUN echo "export TERM=screen-256color" >/.zshenv++CMD zsh -c weechatdiff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/resultnew file mode 100644index 000000000..c3abb4c54--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/weechat/result@@ -0,0 +1,6 @@+(from "ubuntu:14.04")+(run "apt-get update -qy && apt-get install tmux zsh weechat-curses -y")+(add ".weechat" "/.weechat")+(add ".tmux.conf" "/")+(run "echo \"export TERM=screen-256color\" >/.zshenv")+(cmd "zsh -c weechat")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfile b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfilenew file mode 100644index 000000000..626b126d8--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/Dockerfile@@ -0,0 +1,7 @@+FROM ubuntu:14.04+LABEL maintainer Erik Hollensbe <[email protected]>++RUN apt-get update && apt-get install znc -y+ADD conf /.znc++CMD [ "/usr/bin/znc", "-f", "-r" ]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/result b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/resultnew file mode 100644index 000000000..13a9827b2--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/parser/testfiles/znc/result@@ -0,0 +1,5 @@+(from "ubuntu:14.04")+(label "maintainer" "Erik Hollensbe <[email protected]>" "")+(run "apt-get update && apt-get install znc -y")+(add "conf" "/.znc")+(cmd "/usr/bin/znc" "-f" "-r")diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.env.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.env.jsonnew file mode 100644index 000000000..1e9afc3aa--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.env.json@@ -0,0 +1,950 @@+[+ {+ "input": "hello",+ "word": "hello"+ },+ {+ "input": "he'll'o",+ "word": "hello"+ },+ {+ "input": "he'llo",+ "word": null,+ "error": true+ },+ {+ "input": "he\\'llo",+ "word": "he'llo"+ },+ {+ "input": "he\\\\'llo",+ "word": null,+ "error": true+ },+ {+ "input": "abc\\tdef",+ "word": "abctdef"+ },+ {+ "input": "\"abc\\tdef\"",+ "word": "abc\\tdef"+ },+ {+ "input": "\"abc\\\\tdef\"",+ "word": "abc\\tdef"+ },+ {+ "input": "'abc\\tdef'",+ "word": "abc\\tdef"+ },+ {+ "input": "hello\\",+ "word": "hello"+ },+ {+ "input": "hello\\\\",+ "word": "hello\\"+ },+ {+ "input": "\"hello",+ "word": null,+ "error": true+ },+ {+ "input": "\"hello\\\"",+ "word": null,+ "error": true+ },+ {+ "input": "\"hel'lo\"",+ "word": "hel'lo"+ },+ {+ "input": "'hello",+ "word": null,+ "error": true+ },+ {+ "input": "'hello\\'",+ "word": "hello\\"+ },+ {+ "input": "'hello\\there'",+ "word": "hello\\there"+ },+ {+ "input": "'hello\\\\there'",+ "word": "hello\\\\there"+ },+ {+ "input": "\"''\"",+ "word": "''"+ },+ {+ "input": "$.",+ "word": "$."+ },+ {+ "input": "he$1x",+ "word": "hex"+ },+ {+ "input": "he$.x",+ "word": "he$.x"+ },+ {+ "input": "he$pwd.",+ "word": "he."+ },+ {+ "input": "he$PWD",+ "word": "he/home"+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD"+ },+ {+ "input": "he\\\\$PWD",+ "word": "he\\/home"+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD"+ },+ {+ "input": "\"he\\\\$PWD\"",+ "word": "he\\/home"+ },+ {+ "input": "\\${}",+ "word": "${}"+ },+ {+ "input": "\\${}aaa",+ "word": "${}aaa"+ },+ {+ "input": "he\\${}",+ "word": "he${}"+ },+ {+ "input": "he\\${}xx",+ "word": "he${}xx"+ },+ {+ "input": "${}",+ "word": null,+ "error": true+ },+ {+ "input": "${}aaa",+ "word": null,+ "error": true+ },+ {+ "input": "he${}",+ "word": null,+ "error": true+ },+ {+ "input": "he${}xx",+ "word": null,+ "error": true+ },+ {+ "input": "he${hi}",+ "word": "he"+ },+ {+ "input": "he${hi}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD}",+ "word": "he/home"+ },+ {+ "input": "he${.}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:-000}xx",+ "word": "he000xx"+ },+ {+ "input": "he${PWD:-000}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-$PWD}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-${PWD:-yyy}}xx",+ "word": "he/homexx"+ },+ {+ "input": "he${XXX:-${YYY:-yyy}}xx",+ "word": "heyyyxx"+ },+ {+ "input": "he${XXX:YYY}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD?}",+ "word": "he/home"+ },+ {+ "input": "he${PWD:?}",+ "word": "he/home"+ },+ {+ "input": "he${NULL?}",+ "word": "he"+ },+ {+ "input": "he${NULL:?}",+ "word": null,+ "error": true+ },+ {+ "input": "he${XXX:+${PWD}}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+${XXX}}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+${SHELL}}xx",+ "word": "hebashxx"+ },+ {+ "input": "he${XXX:+000}xx",+ "word": "hexx"+ },+ {+ "input": "he${PWD:+000}xx",+ "word": "he000xx"+ },+ {+ "input": "'he${XX}'",+ "word": "he${XX}"+ },+ {+ "input": "\"he${PWD}\"",+ "word": "he/home"+ },+ {+ "input": "\"he'$PWD'\"",+ "word": "he'/home'"+ },+ {+ "input": "\"$PWD\"",+ "word": "/home"+ },+ {+ "input": "'$PWD'",+ "word": "$PWD"+ },+ {+ "input": "'\\$PWD'",+ "word": "\\$PWD"+ },+ {+ "input": "'\"hello\"'",+ "word": "\"hello\""+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD"+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD"+ },+ {+ "input": "'he\\$PWD'",+ "word": "he\\$PWD"+ },+ {+ "input": "he${PWD",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD:=000}xx",+ "word": null,+ "error": true+ },+ {+ "input": "he${PWD:+${PWD}:}xx",+ "word": "he/home:xx"+ },+ {+ "input": "he${XXX:-\\$PWD:}xx",+ "word": "he$PWD:xx"+ },+ {+ "input": "he${XXX:-\\${PWD}z}xx",+ "word": "he${PWDz}xx"+ },+ {+ "input": "안녕하세요",+ "word": "안녕하세요"+ },+ {+ "input": "안'녕'하세요",+ "word": "안녕하세요"+ },+ {+ "input": "안'녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕\\'하세요",+ "word": "안녕'하세요"+ },+ {+ "input": "안\\\\'녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕\\t하세요",+ "word": "안녕t하세요"+ },+ {+ "input": "\"안녕\\t하세요\"",+ "word": "안녕\\t하세요"+ },+ {+ "input": "'안녕\\t하세요",+ "word": null,+ "error": true+ },+ {+ "input": "안녕하세요\\",+ "word": "안녕하세요"+ },+ {+ "input": "안녕하세요\\\\",+ "word": "안녕하세요\\"+ },+ {+ "input": "\"안녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "\"안녕하세요\\\"",+ "word": null,+ "error": true+ },+ {+ "input": "\"안녕'하세요\"",+ "word": "안녕'하세요"+ },+ {+ "input": "'안녕하세요",+ "word": null,+ "error": true+ },+ {+ "input": "'안녕하세요\\'",+ "word": "안녕하세요\\"+ },+ {+ "input": "안녕$1x",+ "word": "안녕x"+ },+ {+ "input": "안녕$.x",+ "word": "안녕$.x"+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕."+ },+ {+ "input": "안녕$PWD",+ "word": "안녕/home"+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD"+ },+ {+ "input": "안녕\\\\$PWD",+ "word": "안녕\\/home"+ },+ {+ "input": "안녕\\${}",+ "word": "안녕${}"+ },+ {+ "input": "안녕\\${}xx",+ "word": "안녕${}xx"+ },+ {+ "input": "안녕${}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${}xx",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${hi}",+ "word": "안녕"+ },+ {+ "input": "안녕${hi}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD}",+ "word": "안녕/home"+ },+ {+ "input": "안녕${.}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${XXX:-000}xx",+ "word": "안녕000xx"+ },+ {+ "input": "안녕${PWD:-000}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-$PWD}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-${PWD:-yyy}}xx",+ "word": "안녕/homexx"+ },+ {+ "input": "안녕${XXX:-${YYY:-yyy}}xx",+ "word": "안녕yyyxx"+ },+ {+ "input": "안녕${XXX:YYY}",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${XXX:+${PWD}}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+${XXX}}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+${SHELL}}xx",+ "word": "안녕bashxx"+ },+ {+ "input": "안녕${XXX:+000}xx",+ "word": "안녕xx"+ },+ {+ "input": "안녕${PWD:+000}xx",+ "word": "안녕000xx"+ },+ {+ "input": "'안녕${XX}'",+ "word": "안녕${XX}"+ },+ {+ "input": "\"안녕${PWD}\"",+ "word": "안녕/home"+ },+ {+ "input": "\"안녕'$PWD'\"",+ "word": "안녕'/home'"+ },+ {+ "input": "'\"안녕\"'",+ "word": "\"안녕\""+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD"+ },+ {+ "input": "\"안녕\\$PWD\"",+ "word": "안녕$PWD"+ },+ {+ "input": "'안녕\\$PWD'",+ "word": "안녕\\$PWD"+ },+ {+ "input": "안녕${PWD",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${PWD:=000}xx",+ "word": null,+ "error": true+ },+ {+ "input": "안녕${PWD:+${PWD}:}xx",+ "word": "안녕/home:xx"+ },+ {+ "input": "안녕${XXX:-\\$PWD:}xx",+ "word": "안녕$PWD:xx"+ },+ {+ "input": "안녕${XXX:-\\${PWD}z}xx",+ "word": "안녕${PWDz}xx"+ },+ {+ "input": "$KOREAN",+ "word": "한국어"+ },+ {+ "input": "안녕$KOREAN",+ "word": "안녕한국어"+ },+ {+ "input": "${{aaa}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa}}",+ "word": "}"+ },+ {+ "input": "${aaa",+ "word": null,+ "error": true+ },+ {+ "input": "${{aaa:-bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb}}",+ "word": "bbb}"+ },+ {+ "input": "${aaa:-bbb",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb}",+ "word": "bbb"+ },+ {+ "input": "${aaa:-${bbb:-ccc}}",+ "word": "ccc"+ },+ {+ "input": "${aaa:-bbb ${foo}",+ "word": null,+ "error": true+ },+ {+ "input": "${aaa:-bbb {foo}",+ "word": "bbb {foo"+ },+ {+ "input": "${:}",+ "word": null,+ "error": true+ },+ {+ "input": "${:-bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "${:+bbb}",+ "word": null,+ "error": true+ },+ {+ "input": "$1",+ "word": ""+ },+ {+ "input": "${1}",+ "word": ""+ },+ {+ "input": "${1:+bbb}",+ "word": ""+ },+ {+ "input": "${1:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$2",+ "word": ""+ },+ {+ "input": "${2}",+ "word": ""+ },+ {+ "input": "${2:+bbb}",+ "word": ""+ },+ {+ "input": "${2:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$3",+ "word": ""+ },+ {+ "input": "${3}",+ "word": ""+ },+ {+ "input": "${3:+bbb}",+ "word": ""+ },+ {+ "input": "${3:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$4",+ "word": ""+ },+ {+ "input": "${4}",+ "word": ""+ },+ {+ "input": "${4:+bbb}",+ "word": ""+ },+ {+ "input": "${4:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$5",+ "word": ""+ },+ {+ "input": "${5}",+ "word": ""+ },+ {+ "input": "${5:+bbb}",+ "word": ""+ },+ {+ "input": "${5:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$6",+ "word": ""+ },+ {+ "input": "${6}",+ "word": ""+ },+ {+ "input": "${6:+bbb}",+ "word": ""+ },+ {+ "input": "${6:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$7",+ "word": ""+ },+ {+ "input": "${7}",+ "word": ""+ },+ {+ "input": "${7:+bbb}",+ "word": ""+ },+ {+ "input": "${7:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$8",+ "word": ""+ },+ {+ "input": "${8}",+ "word": ""+ },+ {+ "input": "${8:+bbb}",+ "word": ""+ },+ {+ "input": "${8:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$9",+ "word": ""+ },+ {+ "input": "${9}",+ "word": ""+ },+ {+ "input": "${9:+bbb}",+ "word": ""+ },+ {+ "input": "${9:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$999",+ "word": ""+ },+ {+ "input": "${999}",+ "word": ""+ },+ {+ "input": "${999:+bbb}",+ "word": ""+ },+ {+ "input": "${999:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$999aaa",+ "word": "aaa"+ },+ {+ "input": "${999}aaa",+ "word": "aaa"+ },+ {+ "input": "${999:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${999:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$001",+ "word": ""+ },+ {+ "input": "${001}",+ "word": ""+ },+ {+ "input": "${001:+bbb}",+ "word": ""+ },+ {+ "input": "${001:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$001aaa",+ "word": "aaa"+ },+ {+ "input": "${001}aaa",+ "word": "aaa"+ },+ {+ "input": "${001:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${001:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$@",+ "word": ""+ },+ {+ "input": "${@}",+ "word": ""+ },+ {+ "input": "${@:+bbb}",+ "word": ""+ },+ {+ "input": "${@:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$@@@",+ "word": "@@"+ },+ {+ "input": "$@aaa",+ "word": "aaa"+ },+ {+ "input": "${@}aaa",+ "word": "aaa"+ },+ {+ "input": "${@:+bbb}aaa",+ "word": "aaa"+ },+ {+ "input": "${@:-bbb}aaa",+ "word": "bbbaaa"+ },+ {+ "input": "$*",+ "word": ""+ },+ {+ "input": "${*}",+ "word": ""+ },+ {+ "input": "${*:+bbb}",+ "word": ""+ },+ {+ "input": "${*:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$#",+ "word": ""+ },+ {+ "input": "${#}",+ "word": ""+ },+ {+ "input": "${#:+bbb}",+ "word": ""+ },+ {+ "input": "${#:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$?",+ "word": ""+ },+ {+ "input": "${?}",+ "word": ""+ },+ {+ "input": "${?:+bbb}",+ "word": ""+ },+ {+ "input": "${?:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$-",+ "word": ""+ },+ {+ "input": "${-}",+ "word": ""+ },+ {+ "input": "${-:+bbb}",+ "word": ""+ },+ {+ "input": "${-:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$$",+ "word": ""+ },+ {+ "input": "${$}",+ "word": ""+ },+ {+ "input": "${$:+bbb}",+ "word": ""+ },+ {+ "input": "${$:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$!",+ "word": ""+ },+ {+ "input": "${!}",+ "word": ""+ },+ {+ "input": "${!:+bbb}",+ "word": ""+ },+ {+ "input": "${!:-bbb}",+ "word": "bbb"+ },+ {+ "input": "$0",+ "word": ""+ },+ {+ "input": "${0}",+ "word": ""+ },+ {+ "input": "${0:+bbb}",+ "word": ""+ },+ {+ "input": "${0:-bbb}",+ "word": "bbb"+ }+]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.jsonnew file mode 100644index 000000000..fe3ee8de4--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/envVarTest.json@@ -0,0 +1,1692 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": [+ "hello"+ ]+ },+ {+ "input": "he'll'o",+ "word": "hello",+ "words": [+ "hello"+ ]+ },+ {+ "input": "he'llo",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he\\'llo",+ "word": "he'llo",+ "words": [+ "he'llo"+ ]+ },+ {+ "input": "he\\\\'llo",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "abc\\tdef",+ "word": "abctdef",+ "words": [+ "abctdef"+ ]+ },+ {+ "input": "\"abc\\tdef\"",+ "word": "abc\\tdef",+ "words": [+ "abc\\tdef"+ ]+ },+ {+ "input": "\"abc\\\\tdef\"",+ "word": "abc\\tdef",+ "words": [+ "abc\\tdef"+ ]+ },+ {+ "input": "'abc\\tdef'",+ "word": "abc\\tdef",+ "words": [+ "abc\\tdef"+ ]+ },+ {+ "input": "hello\\",+ "word": "hello",+ "words": [+ "hello"+ ]+ },+ {+ "input": "hello\\\\",+ "word": "hello\\",+ "words": [+ "hello\\"+ ]+ },+ {+ "input": "\"hello",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"hello\\\"",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"hel'lo\"",+ "word": "hel'lo",+ "words": [+ "hel'lo"+ ]+ },+ {+ "input": "'hello",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "'hello\\'",+ "word": "hello\\",+ "words": [+ "hello\\"+ ]+ },+ {+ "input": "'hello\\there'",+ "word": "hello\\there",+ "words": [+ "hello\\there"+ ]+ },+ {+ "input": "'hello\\\\there'",+ "word": "hello\\\\there",+ "words": [+ "hello\\\\there"+ ]+ },+ {+ "input": "\"''\"",+ "word": "''",+ "words": [+ "''"+ ]+ },+ {+ "input": "$.",+ "word": "$.",+ "words": [+ "$."+ ]+ },+ {+ "input": "he$1x",+ "word": "he$1x",+ "words": [+ "he$1x"+ ]+ },+ {+ "input": "he$.x",+ "word": "he$.x",+ "words": [+ "he$.x"+ ]+ },+ {+ "input": "he$pwd.",+ "word": "he$pwd.",+ "words": [+ "he$pwd."+ ]+ },+ {+ "input": "he$pwd.",+ "word": "he$pwd.",+ "words": [+ "he$pwd."+ ]+ },+ {+ "input": "he$PWD",+ "word": "he$PWD",+ "words": [+ "he$PWD"+ ]+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD",+ "words": [+ "he$PWD"+ ]+ },+ {+ "input": "he\\\\$PWD",+ "word": "he\\$PWD",+ "words": [+ "he\\$PWD"+ ]+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD",+ "words": [+ "he$PWD"+ ]+ },+ {+ "input": "\"he\\\\$PWD\"",+ "word": "he\\$PWD",+ "words": [+ "he\\$PWD"+ ]+ },+ {+ "input": "\\${}",+ "word": "${}",+ "words": [+ "${}"+ ]+ },+ {+ "input": "\\${}aaa",+ "word": "${}aaa",+ "words": [+ "${}aaa"+ ]+ },+ {+ "input": "he\\${}",+ "word": "he${}",+ "words": [+ "he${}"+ ]+ },+ {+ "input": "he\\${}xx",+ "word": "he${}xx",+ "words": [+ "he${}xx"+ ]+ },+ {+ "input": "${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${}aaa",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${}xx",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${hi}",+ "word": "he${hi}",+ "words": [+ "he${hi}"+ ]+ },+ {+ "input": "he${hi}xx",+ "word": "he${hi}xx",+ "words": [+ "he${hi}xx"+ ]+ },+ {+ "input": "he${PWD}",+ "word": "he${PWD}",+ "words": [+ "he${PWD}"+ ]+ },+ {+ "input": "he${.}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${XXX:-000}xx",+ "word": "he${XXX:-000}xx",+ "words": [+ "he${XXX:-000}xx"+ ],+ "buildkitWords": [+ "${XXX:-000}xx"+ ]+ },+ {+ "input": "he${PWD:-000}xx",+ "word": "he${PWD:-000}xx",+ "words": [+ "he${PWD:-000}xx"+ ],+ "buildkitWords": [+ "${PWD:-000}xx"+ ]+ },+ {+ "input": "he${XXX:-$PWD}xx",+ "word": "he${XXX:-$PWD}xx",+ "words": [+ "he${XXX:-$PWD}xx"+ ],+ "buildkitWords": [+ "${XXX:-$PWD}xx"+ ]+ },+ {+ "input": "he${XXX:-${PWD:-yyy}}xx",+ "word": "he${XXX:-${PWD:-yyy}}xx",+ "words": [+ "he${XXX:-${PWD:-yyy}}xx"+ ],+ "buildkitWords": [+ "${XXX:-${PWD:-yyy}}xx"+ ]+ },+ {+ "input": "he${XXX:-${YYY:-yyy}}xx",+ "word": "he${XXX:-${YYY:-yyy}}xx",+ "words": [+ "he${XXX:-${YYY:-yyy}}xx"+ ],+ "buildkitWords": [+ "${XXX:-${YYY:-yyy}}xx"+ ]+ },+ {+ "input": "he${XXX:YYY}",+ "word": "he${XXX:YYY}",+ "words": [+ "he${XXX:YYY}"+ ],+ "buildkitWords": [+ "${XXX:YYY}"+ ]+ },+ {+ "input": "he${XXX?}",+ "word": "he${XXX?}",+ "words": [+ "he${XXX?}"+ ],+ "buildkitWords": [+ "${XXX?}"+ ]+ },+ {+ "input": "he${XXX:?}",+ "word": "he${XXX:?}",+ "words": [+ "he${XXX:?}"+ ],+ "buildkitWords": [+ "${XXX:?}"+ ]+ },+ {+ "input": "he${PWD?}",+ "word": "he${PWD?}",+ "words": [+ "he${PWD?}"+ ],+ "buildkitWords": [+ "${PWD?}"+ ]+ },+ {+ "input": "he${PWD:?}",+ "word": "he${PWD:?}",+ "words": [+ "he${PWD:?}"+ ],+ "buildkitWords": [+ "${PWD:?}"+ ]+ },+ {+ "input": "he${NULL?}",+ "word": "he${NULL?}",+ "words": [+ "he${NULL?}"+ ],+ "buildkitWords": [+ "${NULL?}"+ ]+ },+ {+ "input": "he${NULL:?}",+ "word": "he${NULL:?}",+ "words": [+ "he${NULL:?}"+ ],+ "buildkitWords": [+ "${NULL:?}"+ ]+ },+ {+ "input": "he${XXX:+${PWD}}xx",+ "word": "he${XXX:+${PWD}}xx",+ "words": [+ "he${XXX:+${PWD}}xx"+ ],+ "buildkitWords": [+ "${XXX:+${PWD}}xx"+ ]+ },+ {+ "input": "he${PWD:+${XXX}}xx",+ "word": "he${PWD:+${XXX}}xx",+ "words": [+ "he${PWD:+${XXX}}xx"+ ],+ "buildkitWords": [+ "${PWD:+${XXX}}xx"+ ]+ },+ {+ "input": "he${PWD:+${SHELL}}xx",+ "word": "he${PWD:+${SHELL}}xx",+ "words": [+ "he${PWD:+${SHELL}}xx"+ ],+ "buildkitWords": [+ "${PWD:+${SHELL}}xx"+ ]+ },+ {+ "input": "he${XXX:+000}xx",+ "word": "he${XXX:+000}xx",+ "words": [+ "he${XXX:+000}xx"+ ],+ "buildkitWords": [+ "${XXX:+000}xx"+ ]+ },+ {+ "input": "he${PWD:+000}xx",+ "word": "he${PWD:+000}xx",+ "words": [+ "he${PWD:+000}xx"+ ],+ "buildkitWords": [+ "${PWD:+000}xx"+ ]+ },+ {+ "input": "'he${XX}'",+ "word": "he${XX}",+ "words": [+ "he${XX}"+ ]+ },+ {+ "input": "\"he${PWD}\"",+ "word": "he${PWD}",+ "words": [+ "he${PWD}"+ ]+ },+ {+ "input": "\"he'$PWD'\"",+ "word": "he'$PWD'",+ "words": [+ "he'$PWD'"+ ]+ },+ {+ "input": "\"$PWD\"",+ "word": "$PWD",+ "words": [+ "$PWD"+ ]+ },+ {+ "input": "'$PWD'",+ "word": "$PWD",+ "words": [+ "$PWD"+ ]+ },+ {+ "input": "'\\$PWD'",+ "word": "\\$PWD",+ "words": [+ "\\$PWD"+ ]+ },+ {+ "input": "'\"hello\"'",+ "word": "\"hello\"",+ "words": [+ "\"hello\""+ ]+ },+ {+ "input": "he\\$PWD",+ "word": "he$PWD",+ "words": [+ "he$PWD"+ ]+ },+ {+ "input": "\"he\\$PWD\"",+ "word": "he$PWD",+ "words": [+ "he$PWD"+ ]+ },+ {+ "input": "'he\\$PWD'",+ "word": "he\\$PWD",+ "words": [+ "he\\$PWD"+ ]+ },+ {+ "input": "he${PWD",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "he${PWD:=000}xx",+ "word": "he${PWD:=000}xx",+ "words": [+ "he${PWD:=000}xx"+ ],+ "buildkitWords": [+ "${PWD:=000}xx"+ ]+ },+ {+ "input": "he${PWD:+${PWD}:}xx",+ "word": "he${PWD:+${PWD}:}xx",+ "words": [+ "he${PWD:+${PWD}:}xx"+ ],+ "buildkitWords": [+ "${PWD:+${PWD}:}xx"+ ]+ },+ {+ "input": "he${XXX:-\\$PWD:}xx",+ "word": "he${XXX:-$PWD:}xx",+ "words": [+ "he${XXX:-$PWD:}xx"+ ],+ "buildkitWords": [+ "${XXX:-$PWD:}xx"+ ]+ },+ {+ "input": "he${XXX:-\\${PWD}z}xx",+ "word": "he${XXX:-${PWD}z}xx",+ "words": [+ "he${XXX:-${PWD}z}xx"+ ],+ "buildkitWords": [+ "${XXX:-${PWD}z}xx"+ ]+ },+ {+ "input": "안녕하세요",+ "word": "안녕하세요",+ "words": [+ "안녕하세요"+ ]+ },+ {+ "input": "안'녕'하세요",+ "word": "안녕하세요",+ "words": [+ "안녕하세요"+ ]+ },+ {+ "input": "안'녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕\\'하세요",+ "word": "안녕'하세요",+ "words": [+ "안녕'하세요"+ ]+ },+ {+ "input": "안\\\\'녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕\\t하세요",+ "word": "안녕t하세요",+ "words": [+ "안녕t하세요"+ ]+ },+ {+ "input": "\"안녕\\t하세요\"",+ "word": "안녕\\t하세요",+ "words": [+ "안녕\\t하세요"+ ]+ },+ {+ "input": "'안녕\\t하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕하세요\\",+ "word": "안녕하세요",+ "words": [+ "안녕하세요"+ ]+ },+ {+ "input": "안녕하세요\\\\",+ "word": "안녕하세요\\",+ "words": [+ "안녕하세요\\"+ ]+ },+ {+ "input": "\"안녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"안녕하세요\\\"",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "\"안녕'하세요\"",+ "word": "안녕'하세요",+ "words": [+ "안녕'하세요"+ ]+ },+ {+ "input": "'안녕하세요",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "'안녕하세요\\'",+ "word": "안녕하세요\\",+ "words": [+ "안녕하세요\\"+ ]+ },+ {+ "input": "안녕$1x",+ "word": "안녕$1x",+ "words": [+ "안녕$1x"+ ]+ },+ {+ "input": "안녕$.x",+ "word": "안녕$.x",+ "words": [+ "안녕$.x"+ ]+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕$pwd.",+ "words": [+ "안녕$pwd."+ ]+ },+ {+ "input": "안녕$pwd.",+ "word": "안녕$pwd.",+ "words": [+ "안녕$pwd."+ ]+ },+ {+ "input": "안녕$PWD",+ "word": "안녕$PWD",+ "words": [+ "안녕$PWD"+ ]+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD",+ "words": [+ "안녕$PWD"+ ]+ },+ {+ "input": "안녕\\\\$PWD",+ "word": "안녕\\$PWD",+ "words": [+ "안녕\\$PWD"+ ]+ },+ {+ "input": "안녕\\${}",+ "word": "안녕${}",+ "words": [+ "안녕${}"+ ]+ },+ {+ "input": "안녕\\${}xx",+ "word": "안녕${}xx",+ "words": [+ "안녕${}xx"+ ]+ },+ {+ "input": "안녕${}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${}xx",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${hi}",+ "word": "안녕${hi}",+ "words": [+ "안녕${hi}"+ ]+ },+ {+ "input": "안녕${hi}xx",+ "word": "안녕${hi}xx",+ "words": [+ "안녕${hi}xx"+ ]+ },+ {+ "input": "안녕${PWD}",+ "word": "안녕${PWD}",+ "words": [+ "안녕${PWD}"+ ]+ },+ {+ "input": "안녕${.}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${XXX:-000}xx",+ "word": "안녕${XXX:-000}xx",+ "words": [+ "안녕${XXX:-000}xx"+ ],+ "buildkitWords": [+ "${XXX:-000}xx"+ ]+ },+ {+ "input": "안녕${PWD:-000}xx",+ "word": "안녕${PWD:-000}xx",+ "words": [+ "안녕${PWD:-000}xx"+ ],+ "buildkitWords": [+ "${PWD:-000}xx"+ ]+ },+ {+ "input": "안녕${XXX:-$PWD}xx",+ "word": "안녕${XXX:-$PWD}xx",+ "words": [+ "안녕${XXX:-$PWD}xx"+ ],+ "buildkitWords": [+ "${XXX:-$PWD}xx"+ ]+ },+ {+ "input": "안녕${XXX:-${PWD:-yyy}}xx",+ "word": "안녕${XXX:-${PWD:-yyy}}xx",+ "words": [+ "안녕${XXX:-${PWD:-yyy}}xx"+ ],+ "buildkitWords": [+ "${XXX:-${PWD:-yyy}}xx"+ ]+ },+ {+ "input": "안녕${XXX:-${YYY:-yyy}}xx",+ "word": "안녕${XXX:-${YYY:-yyy}}xx",+ "words": [+ "안녕${XXX:-${YYY:-yyy}}xx"+ ],+ "buildkitWords": [+ "${XXX:-${YYY:-yyy}}xx"+ ]+ },+ {+ "input": "안녕${XXX:YYY}",+ "word": "안녕${XXX:YYY}",+ "words": [+ "안녕${XXX:YYY}"+ ],+ "buildkitWords": [+ "${XXX:YYY}"+ ]+ },+ {+ "input": "안녕${XXX:+${PWD}}xx",+ "word": "안녕${XXX:+${PWD}}xx",+ "words": [+ "안녕${XXX:+${PWD}}xx"+ ],+ "buildkitWords": [+ "${XXX:+${PWD}}xx"+ ]+ },+ {+ "input": "안녕${PWD:+${XXX}}xx",+ "word": "안녕${PWD:+${XXX}}xx",+ "words": [+ "안녕${PWD:+${XXX}}xx"+ ],+ "buildkitWords": [+ "${PWD:+${XXX}}xx"+ ]+ },+ {+ "input": "안녕${PWD:+${SHELL}}xx",+ "word": "안녕${PWD:+${SHELL}}xx",+ "words": [+ "안녕${PWD:+${SHELL}}xx"+ ],+ "buildkitWords": [+ "${PWD:+${SHELL}}xx"+ ]+ },+ {+ "input": "안녕${XXX:+000}xx",+ "word": "안녕${XXX:+000}xx",+ "words": [+ "안녕${XXX:+000}xx"+ ],+ "buildkitWords": [+ "${XXX:+000}xx"+ ]+ },+ {+ "input": "안녕${PWD:+000}xx",+ "word": "안녕${PWD:+000}xx",+ "words": [+ "안녕${PWD:+000}xx"+ ],+ "buildkitWords": [+ "${PWD:+000}xx"+ ]+ },+ {+ "input": "'안녕${XX}'",+ "word": "안녕${XX}",+ "words": [+ "안녕${XX}"+ ]+ },+ {+ "input": "\"안녕${PWD}\"",+ "word": "안녕${PWD}",+ "words": [+ "안녕${PWD}"+ ]+ },+ {+ "input": "\"안녕'$PWD'\"",+ "word": "안녕'$PWD'",+ "words": [+ "안녕'$PWD'"+ ]+ },+ {+ "input": "'\"안녕\"'",+ "word": "\"안녕\"",+ "words": [+ "\"안녕\""+ ]+ },+ {+ "input": "안녕\\$PWD",+ "word": "안녕$PWD",+ "words": [+ "안녕$PWD"+ ]+ },+ {+ "input": "\"안녕\\$PWD\"",+ "word": "안녕$PWD",+ "words": [+ "안녕$PWD"+ ]+ },+ {+ "input": "'안녕\\$PWD'",+ "word": "안녕\\$PWD",+ "words": [+ "안녕\\$PWD"+ ]+ },+ {+ "input": "안녕${PWD",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "안녕${PWD:=000}xx",+ "word": "안녕${PWD:=000}xx",+ "words": [+ "안녕${PWD:=000}xx"+ ],+ "buildkitWords": [+ "${PWD:=000}xx"+ ]+ },+ {+ "input": "안녕${PWD:+${PWD}:}xx",+ "word": "안녕${PWD:+${PWD}:}xx",+ "words": [+ "안녕${PWD:+${PWD}:}xx"+ ],+ "buildkitWords": [+ "${PWD:+${PWD}:}xx"+ ]+ },+ {+ "input": "안녕${XXX:-\\$PWD:}xx",+ "word": "안녕${XXX:-$PWD:}xx",+ "words": [+ "안녕${XXX:-$PWD:}xx"+ ],+ "buildkitWords": [+ "${XXX:-$PWD:}xx"+ ]+ },+ {+ "input": "안녕${XXX:-\\${PWD}z}xx",+ "word": "안녕${XXX:-${PWD}z}xx",+ "words": [+ "안녕${XXX:-${PWD}z}xx"+ ],+ "buildkitWords": [+ "${XXX:-${PWD}z}xx"+ ]+ },+ {+ "input": "$KOREAN",+ "word": "$KOREAN",+ "words": [+ "$KOREAN"+ ]+ },+ {+ "input": "안녕$KOREAN",+ "word": "안녕$KOREAN",+ "words": [+ "안녕$KOREAN"+ ]+ },+ {+ "input": "${{aaa}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa}}",+ "word": "${aaa}}",+ "words": [+ "${aaa}}"+ ]+ },+ {+ "input": "${aaa",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${{aaa:-bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb}}",+ "word": "${aaa:-bbb}}",+ "words": [+ "${aaa:-bbb}}"+ ]+ },+ {+ "input": "${aaa:-bbb",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb}",+ "word": "${aaa:-bbb}",+ "words": [+ "${aaa:-bbb}"+ ]+ },+ {+ "input": "${aaa:-${bbb:-ccc}}",+ "word": "${aaa:-${bbb:-ccc}}",+ "words": [+ "${aaa:-${bbb:-ccc}}"+ ]+ },+ {+ "input": "${aaa:-bbb ${foo}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${aaa:-bbb {foo}",+ "word": "${aaa:-bbb {foo}",+ "words": [+ "${aaa:-bbb",+ "{foo}"+ ]+ },+ {+ "input": "${:}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${:-bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "${:+bbb}",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "$1",+ "word": "$1",+ "words": [+ "$1"+ ]+ },+ {+ "input": "${1}",+ "word": "${1}",+ "words": [+ "${1}"+ ]+ },+ {+ "input": "${1:+bbb}",+ "word": "${1:+bbb}",+ "words": [+ "${1:+bbb}"+ ]+ },+ {+ "input": "${1:-bbb}",+ "word": "${1:-bbb}",+ "words": [+ "${1:-bbb}"+ ]+ },+ {+ "input": "$2",+ "word": "$2",+ "words": [+ "$2"+ ]+ },+ {+ "input": "${2}",+ "word": "${2}",+ "words": [+ "${2}"+ ]+ },+ {+ "input": "${2:+bbb}",+ "word": "${2:+bbb}",+ "words": [+ "${2:+bbb}"+ ]+ },+ {+ "input": "${2:-bbb}",+ "word": "${2:-bbb}",+ "words": [+ "${2:-bbb}"+ ]+ },+ {+ "input": "$3",+ "word": "$3",+ "words": [+ "$3"+ ]+ },+ {+ "input": "${3}",+ "word": "${3}",+ "words": [+ "${3}"+ ]+ },+ {+ "input": "${3:+bbb}",+ "word": "${3:+bbb}",+ "words": [+ "${3:+bbb}"+ ]+ },+ {+ "input": "${3:-bbb}",+ "word": "${3:-bbb}",+ "words": [+ "${3:-bbb}"+ ]+ },+ {+ "input": "$4",+ "word": "$4",+ "words": [+ "$4"+ ]+ },+ {+ "input": "${4}",+ "word": "${4}",+ "words": [+ "${4}"+ ]+ },+ {+ "input": "${4:+bbb}",+ "word": "${4:+bbb}",+ "words": [+ "${4:+bbb}"+ ]+ },+ {+ "input": "${4:-bbb}",+ "word": "${4:-bbb}",+ "words": [+ "${4:-bbb}"+ ]+ },+ {+ "input": "$5",+ "word": "$5",+ "words": [+ "$5"+ ]+ },+ {+ "input": "${5}",+ "word": "${5}",+ "words": [+ "${5}"+ ]+ },+ {+ "input": "${5:+bbb}",+ "word": "${5:+bbb}",+ "words": [+ "${5:+bbb}"+ ]+ },+ {+ "input": "${5:-bbb}",+ "word": "${5:-bbb}",+ "words": [+ "${5:-bbb}"+ ]+ },+ {+ "input": "$6",+ "word": "$6",+ "words": [+ "$6"+ ]+ },+ {+ "input": "${6}",+ "word": "${6}",+ "words": [+ "${6}"+ ]+ },+ {+ "input": "${6:+bbb}",+ "word": "${6:+bbb}",+ "words": [+ "${6:+bbb}"+ ]+ },+ {+ "input": "${6:-bbb}",+ "word": "${6:-bbb}",+ "words": [+ "${6:-bbb}"+ ]+ },+ {+ "input": "$7",+ "word": "$7",+ "words": [+ "$7"+ ]+ },+ {+ "input": "${7}",+ "word": "${7}",+ "words": [+ "${7}"+ ]+ },+ {+ "input": "${7:+bbb}",+ "word": "${7:+bbb}",+ "words": [+ "${7:+bbb}"+ ]+ },+ {+ "input": "${7:-bbb}",+ "word": "${7:-bbb}",+ "words": [+ "${7:-bbb}"+ ]+ },+ {+ "input": "$8",+ "word": "$8",+ "words": [+ "$8"+ ]+ },+ {+ "input": "${8}",+ "word": "${8}",+ "words": [+ "${8}"+ ]+ },+ {+ "input": "${8:+bbb}",+ "word": "${8:+bbb}",+ "words": [+ "${8:+bbb}"+ ]+ },+ {+ "input": "${8:-bbb}",+ "word": "${8:-bbb}",+ "words": [+ "${8:-bbb}"+ ]+ },+ {+ "input": "$9",+ "word": "$9",+ "words": [+ "$9"+ ]+ },+ {+ "input": "${9}",+ "word": "${9}",+ "words": [+ "${9}"+ ]+ },+ {+ "input": "${9:+bbb}",+ "word": "${9:+bbb}",+ "words": [+ "${9:+bbb}"+ ]+ },+ {+ "input": "${9:-bbb}",+ "word": "${9:-bbb}",+ "words": [+ "${9:-bbb}"+ ]+ },+ {+ "input": "$999",+ "word": "$999",+ "words": [+ "$999"+ ]+ },+ {+ "input": "${999}",+ "word": "${999}",+ "words": [+ "${999}"+ ]+ },+ {+ "input": "${999:+bbb}",+ "word": "${999:+bbb}",+ "words": [+ "${999:+bbb}"+ ]+ },+ {+ "input": "${999:-bbb}",+ "word": "${999:-bbb}",+ "words": [+ "${999:-bbb}"+ ]+ },+ {+ "input": "$999aaa",+ "word": "$999aaa",+ "words": [+ "$999aaa"+ ]+ },+ {+ "input": "${999}aaa",+ "word": "${999}aaa",+ "words": [+ "${999}aaa"+ ]+ },+ {+ "input": "${999:+bbb}aaa",+ "word": "${999:+bbb}aaa",+ "words": [+ "${999:+bbb}aaa"+ ]+ },+ {+ "input": "${999:-bbb}aaa",+ "word": "${999:-bbb}aaa",+ "words": [+ "${999:-bbb}aaa"+ ]+ },+ {+ "input": "$001",+ "word": "$001",+ "words": [+ "$001"+ ]+ },+ {+ "input": "${001}",+ "word": "${001}",+ "words": [+ "${001}"+ ]+ },+ {+ "input": "${001:+bbb}",+ "word": "${001:+bbb}",+ "words": [+ "${001:+bbb}"+ ]+ },+ {+ "input": "${001:-bbb}",+ "word": "${001:-bbb}",+ "words": [+ "${001:-bbb}"+ ]+ },+ {+ "input": "$001aaa",+ "word": "$001aaa",+ "words": [+ "$001aaa"+ ]+ },+ {+ "input": "${001}aaa",+ "word": "${001}aaa",+ "words": [+ "${001}aaa"+ ]+ },+ {+ "input": "${001:+bbb}aaa",+ "word": "${001:+bbb}aaa",+ "words": [+ "${001:+bbb}aaa"+ ]+ },+ {+ "input": "${001:-bbb}aaa",+ "word": "${001:-bbb}aaa",+ "words": [+ "${001:-bbb}aaa"+ ]+ },+ {+ "input": "$@",+ "word": "$@",+ "words": [+ "$@"+ ]+ },+ {+ "input": "${@}",+ "word": "${@}",+ "words": [+ "${@}"+ ]+ },+ {+ "input": "${@:+bbb}",+ "word": "${@:+bbb}",+ "words": [+ "${@:+bbb}"+ ]+ },+ {+ "input": "${@:-bbb}",+ "word": "${@:-bbb}",+ "words": [+ "${@:-bbb}"+ ]+ },+ {+ "input": "$@@@",+ "word": "$@@@",+ "words": [+ "$@@@"+ ]+ },+ {+ "input": "$@aaa",+ "word": "$@aaa",+ "words": [+ "$@aaa"+ ]+ },+ {+ "input": "${@}aaa",+ "word": "${@}aaa",+ "words": [+ "${@}aaa"+ ]+ },+ {+ "input": "${@:+bbb}aaa",+ "word": "${@:+bbb}aaa",+ "words": [+ "${@:+bbb}aaa"+ ]+ },+ {+ "input": "${@:-bbb}aaa",+ "word": "${@:-bbb}aaa",+ "words": [+ "${@:-bbb}aaa"+ ]+ },+ {+ "input": "$*",+ "word": "$*",+ "words": [+ "$*"+ ]+ },+ {+ "input": "${*}",+ "word": "${*}",+ "words": [+ "${*}"+ ]+ },+ {+ "input": "${*:+bbb}",+ "word": "${*:+bbb}",+ "words": [+ "${*:+bbb}"+ ]+ },+ {+ "input": "${*:-bbb}",+ "word": "${*:-bbb}",+ "words": [+ "${*:-bbb}"+ ]+ },+ {+ "input": "$#",+ "word": "$#",+ "words": [+ "$#"+ ]+ },+ {+ "input": "${#}",+ "word": "${#}",+ "words": [+ "${#}"+ ]+ },+ {+ "input": "${#:+bbb}",+ "word": "${#:+bbb}",+ "words": [+ "${#:+bbb}"+ ]+ },+ {+ "input": "${#:-bbb}",+ "word": "${#:-bbb}",+ "words": [+ "${#:-bbb}"+ ]+ },+ {+ "input": "$?",+ "word": "$?",+ "words": [+ "$?"+ ]+ },+ {+ "input": "${?}",+ "word": "${?}",+ "words": [+ "${?}"+ ]+ },+ {+ "input": "${?:+bbb}",+ "word": "${?:+bbb}",+ "words": [+ "${?:+bbb}"+ ]+ },+ {+ "input": "${?:-bbb}",+ "word": "${?:-bbb}",+ "words": [+ "${?:-bbb}"+ ]+ },+ {+ "input": "$-",+ "word": "$-",+ "words": [+ "$-"+ ]+ },+ {+ "input": "${-}",+ "word": "${-}",+ "words": [+ "${-}"+ ]+ },+ {+ "input": "${-:+bbb}",+ "word": "${-:+bbb}",+ "words": [+ "${-:+bbb}"+ ]+ },+ {+ "input": "${-:-bbb}",+ "word": "${-:-bbb}",+ "words": [+ "${-:-bbb}"+ ]+ },+ {+ "input": "$$",+ "word": "$$",+ "words": [+ "$$"+ ]+ },+ {+ "input": "${$}",+ "word": "${$}",+ "words": [+ "${$}"+ ]+ },+ {+ "input": "${$:+bbb}",+ "word": "${$:+bbb}",+ "words": [+ "${$:+bbb}"+ ]+ },+ {+ "input": "${$:-bbb}",+ "word": "${$:-bbb}",+ "words": [+ "${$:-bbb}"+ ]+ },+ {+ "input": "$!",+ "word": "$!",+ "words": [+ "$!"+ ]+ },+ {+ "input": "${!}",+ "word": "${!}",+ "words": [+ "${!}"+ ]+ },+ {+ "input": "${!:+bbb}",+ "word": "${!:+bbb}",+ "words": [+ "${!:+bbb}"+ ]+ },+ {+ "input": "${!:-bbb}",+ "word": "${!:-bbb}",+ "words": [+ "${!:-bbb}"+ ]+ },+ {+ "input": "$0",+ "word": "$0",+ "words": [+ "$0"+ ]+ },+ {+ "input": "${0}",+ "word": "${0}",+ "words": [+ "${0}"+ ]+ },+ {+ "input": "${0:+bbb}",+ "word": "${0:+bbb}",+ "words": [+ "${0:+bbb}"+ ]+ },+ {+ "input": "${0:-bbb}",+ "word": "${0:-bbb}",+ "words": [+ "${0:-bbb}"+ ]+ }+]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/processWithMatches.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/processWithMatches.jsonnew file mode 100644index 000000000..f8ddc5a6b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/processWithMatches.json@@ -0,0 +1,341 @@+[+ {+ "input": "x",+ "env": {+ "DUMMY": "dummy"+ },+ "word": "x"+ },+ {+ "input": "x ${UNUSED}",+ "env": {+ "DUMMY": "dummy"+ },+ "word": "x "+ },+ {+ "input": "x ${FOO}",+ "env": {+ "FOO": "y"+ },+ "word": "x y"+ },+ {+ "input": "${FOO-aaa} ${BAR-bbb} ${BAZ-ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx ccc"+ },+ {+ "input": "${FOO:-aaa} ${BAR:-bbb} ${BAZ:-ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx bbb ccc"+ },+ {+ "input": "${FOO:-}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${FOO:-}",+ "env": {},+ "word": ""+ },+ {+ "input": "${FOO+aaa} ${BAR+bbb} ${BAZ+ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "aaa bbb "+ },+ {+ "input": "${FOO:+aaa} ${BAR:+bbb} ${BAZ:+ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "aaa "+ },+ {+ "input": "${FOO?aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${BAR?bbb}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": ""+ },+ {+ "input": "${BAZ?ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO:?aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "word": "xxx"+ },+ {+ "input": "${BAR:?bbb}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${BAZ:?ccc}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${BAZ:?}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=:aaa}",+ "env": {+ "FOO": "xxx",+ "BAR": ""+ },+ "error": true+ },+ {+ "input": "${FOO=}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO#()[]{\\}^$.\\*\\?|\\\\}",+ "env": {+ "FOO": "()[]{}^$.*?|\\x"+ },+ "word": "x"+ },+ {+ "input": "${FOO%%\\**}",+ "env": {+ "FOO": "xx**"+ },+ "word": "xx"+ },+ {+ "input": "${FOO#*x*y}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "y"+ },+ {+ "input": "${FOO#*}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": "x"+ },+ "word": "xyy"+ },+ {+ "input": "${FOO#$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO##*x}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "yy"+ },+ {+ "input": "${FOO##}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO#?\\?}",+ "env": {+ "FOO": "???y"+ },+ "word": "?y"+ },+ {+ "input": "${ABC:-.}${FOO%x}${ABC:-.}",+ "env": {+ "FOO": "xxyy"+ },+ "word": ".xxyy."+ },+ {+ "input": "${FOO%%\\**\\*}",+ "env": {+ "FOO": "a***yy*"+ },+ "word": "a"+ },+ {+ "input": "${FOO%}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO%%$BAR}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO:#}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:##}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:%}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO:%%}",+ "env": {},+ "error": true+ },+ {+ "input": "${FOO/$NEEDLE/.} - ${FOO//$NEEDLE/.}",+ "env": {+ "FOO": "/foo*/*/*.txt",+ "NEEDLE": "\\*/"+ },+ "word": "/foo.*/*.txt - /foo..*.txt"+ },+ {+ "input": "${FOO/$NEEDLE/} - ${FOO//$NEEDLE/}",+ "env": {+ "FOO": "/tmp/tmp/bar.txt",+ "NEEDLE": "/tmp"+ },+ "word": "/tmp/bar.txt - /bar.txt"+ },+ {+ "input": "${FOO/$NEEDLE/$REPLACEMENT} - ${FOO//$NEEDLE/$REPLACEMENT}",+ "env": {+ "FOO": "/a/foo/b/c.txt",+ "NEEDLE": "/?/",+ "REPLACEMENT": "/"+ },+ "word": "/foo/b/c.txt - /foo/c.txt"+ },+ {+ "input": "${FOO/$NEEDLE/$REPLACEMENT}",+ "env": {+ "FOO": "http://google.de",+ "NEEDLE": "http://",+ "REPLACEMENT": "https://"+ },+ "word": "https://google.de"+ },+ {+ "input": "${FOO//\\//\\/}",+ "env": {+ "FOO": "/tmp/foo.txt"+ },+ "word": "\\/tmp\\/foo.txt"+ },+ {+ "input": "${FOO/$BAR/ww}",+ "env": {+ "FOO": "xxyy",+ "BAR": ""+ },+ "word": "wwxxyy"+ },+ {+ "input": "${FOO//ww}",+ "env": {+ "FOO": "xxyy"+ },+ "error": true+ },+ {+ "input": "${FOO//}",+ "env": {+ "FOO": "xxyy"+ },+ "error": true+ },+ {+ "input": "${FOO///}",+ "env": {+ "FOO": "xxyy"+ },+ "word": "xxyy"+ },+ {+ "input": "${FOO///}",+ "env": {},+ "word": ""+ }+]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.env.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.env.jsonnew file mode 100644index 000000000..2b9733a33--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.env.json@@ -0,0 +1,219 @@+[+ {+ "input": "hello",+ "env": {},+ "words": ["hello"]+ },+ {+ "input": "hello${hi}bye",+ "env": {},+ "words": ["hellobye"]+ },+ {+ "input": "hello${hi}bye",+ "env": {+ "hi": "hi"+ },+ "words": ["hellohibye"]+ },+ {+ "input": "hello${space}bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["helloabc", "defbye"]+ },+ {+ "input": "hello\"${space}\"bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["helloabc defbye"]+ },+ {+ "input": "hello \"${space}\"bye",+ "env": {+ "hi": "hi",+ "space": "abc def"+ },+ "words": ["hello", "abc defbye"]+ },+ {+ "input": "hello${leading}def",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello", "ab", "cdef"]+ },+ {+ "input": "hello\"${leading}\" def",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello ab c", "def"]+ },+ {+ "input": "hello\"${leading}\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello ab c"]+ },+ {+ "input": "hello${leading}",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c"+ },+ "words": ["hello", "ab", "c"]+ },+ {+ "input": "hello${trailing}",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab", "c"]+ },+ {+ "input": "hello${trailing}d",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab", "c", "d"]+ },+ {+ "input": "hello\"${trailing}\"d",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab c d"]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["helloab c "]+ },+ {+ "input": "hello\" there \"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello there "]+ },+ {+ "input": "hello there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello", "there"]+ },+ {+ "input": "hello\\ there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello there"]+ },+ {+ "input": "hello\" there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "error": true+ },+ {+ "input": "hello\\\" there",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\"", "there"]+ },+ {+ "input": "hello\"\\\\there\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello\"\\there\"",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello'\\\\there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\\\there"]+ },+ {+ "input": "hello'\\there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello\\there"]+ },+ {+ "input": "hello'$there'",+ "env": {+ "hi": "hi",+ "space": "abc def",+ "leading": " ab c",+ "trailing": "ab c "+ },+ "words": ["hello$there"]+ }+]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.jsonnew file mode 100644index 000000000..c6c5b8939--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.json@@ -0,0 +1,173 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": [+ "hello"+ ]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": [+ "hello${hi}bye"+ ]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": [+ "hello${hi}bye"+ ]+ },+ {+ "input": "hello${space}bye",+ "word": "hello${space}bye",+ "words": [+ "hello${space}bye"+ ]+ },+ {+ "input": "hello\"${space}\"bye",+ "word": "hello${space}bye",+ "words": [+ "hello${space}bye"+ ]+ },+ {+ "input": "hello \"${space}\"bye",+ "word": "hello ${space}bye",+ "words": [+ "hello",+ "${space}bye"+ ]+ },+ {+ "input": "hello${leading}def",+ "word": "hello${leading}def",+ "words": [+ "hello${leading}def"+ ]+ },+ {+ "input": "hello\"${leading}\" def",+ "word": "hello${leading} def",+ "words": [+ "hello${leading}",+ "def"+ ]+ },+ {+ "input": "hello\"${leading}\"",+ "word": "hello${leading}",+ "words": [+ "hello${leading}"+ ]+ },+ {+ "input": "hello${leading}",+ "word": "hello${leading}",+ "words": [+ "hello${leading}"+ ]+ },+ {+ "input": "hello${trailing}",+ "word": "hello${trailing}",+ "words": [+ "hello${trailing}"+ ]+ },+ {+ "input": "hello${trailing}d",+ "word": "hello${trailing}d",+ "words": [+ "hello${trailing}d"+ ]+ },+ {+ "input": "hello\"${trailing}\"d",+ "word": "hello${trailing}d",+ "words": [+ "hello${trailing}d"+ ]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "word": "hello${trailing}",+ "words": [+ "hello${trailing}"+ ]+ },+ {+ "input": "hello\" there \"",+ "word": "hello there ",+ "words": [+ "hello there "+ ]+ },+ {+ "input": "hello there",+ "word": "hello there",+ "words": [+ "hello",+ "there"+ ]+ },+ {+ "input": "hello\\ there",+ "word": "hello there",+ "words": [+ "hello there"+ ]+ },+ {+ "input": "hello\" there",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "hello\\\" there",+ "word": "hello\" there",+ "words": [+ "hello\"",+ "there"+ ]+ },+ {+ "input": "hello\"\\\\there\"",+ "word": "hello\\there",+ "words": [+ "hello\\there"+ ]+ },+ {+ "input": "hello\"\\there\"",+ "word": "hello\\there",+ "words": [+ "hello\\there"+ ]+ },+ {+ "input": "hello'\\\\there'",+ "word": "hello\\\\there",+ "words": [+ "hello\\\\there"+ ]+ },+ {+ "input": "hello'\\there'",+ "word": "hello\\there",+ "words": [+ "hello\\there"+ ]+ },+ {+ "input": "hello'$there'",+ "word": "hello$there",+ "words": [+ "hello$there"+ ]+ }+]diff --git a/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.json b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.jsonnew file mode 100644index 000000000..d6dcd6812--- /dev/null+++ b/packages/dockerfile-utils-python/tests/fixtures/buildkit/shell/wordsTest.rawQuotes.json@@ -0,0 +1,173 @@+[+ {+ "input": "hello",+ "word": "hello",+ "words": [+ "hello"+ ]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": [+ "hello${hi}bye"+ ]+ },+ {+ "input": "hello${hi}bye",+ "word": "hello${hi}bye",+ "words": [+ "hello${hi}bye"+ ]+ },+ {+ "input": "hello${space}bye",+ "word": "hello${space}bye",+ "words": [+ "hello${space}bye"+ ]+ },+ {+ "input": "hello\"${space}\"bye",+ "word": "hello\"${space}\"bye",+ "words": [+ "hello\"${space}\"bye"+ ]+ },+ {+ "input": "hello \"${space}\"bye",+ "word": "hello \"${space}\"bye",+ "words": [+ "hello",+ "\"${space}\"bye"+ ]+ },+ {+ "input": "hello${leading}def",+ "word": "hello${leading}def",+ "words": [+ "hello${leading}def"+ ]+ },+ {+ "input": "hello\"${leading}\" def",+ "word": "hello\"${leading}\" def",+ "words": [+ "hello\"${leading}\"",+ "def"+ ]+ },+ {+ "input": "hello\"${leading}\"",+ "word": "hello\"${leading}\"",+ "words": [+ "hello\"${leading}\""+ ]+ },+ {+ "input": "hello${leading}",+ "word": "hello${leading}",+ "words": [+ "hello${leading}"+ ]+ },+ {+ "input": "hello${trailing}",+ "word": "hello${trailing}",+ "words": [+ "hello${trailing}"+ ]+ },+ {+ "input": "hello${trailing}d",+ "word": "hello${trailing}d",+ "words": [+ "hello${trailing}d"+ ]+ },+ {+ "input": "hello\"${trailing}\"d",+ "word": "hello\"${trailing}\"d",+ "words": [+ "hello\"${trailing}\"d"+ ]+ },+ {+ "input": "hel\"lo${trailing}\"",+ "word": "hel\"lo${trailing}\"",+ "words": [+ "hel\"lo${trailing}\""+ ]+ },+ {+ "input": "hello\" there \"",+ "word": "hello\" there \"",+ "words": [+ "hello\" there \""+ ]+ },+ {+ "input": "hello there",+ "word": "hello there",+ "words": [+ "hello",+ "there"+ ]+ },+ {+ "input": "hello\\ there",+ "word": "hello there",+ "words": [+ "hello there"+ ]+ },+ {+ "input": "hello\" there",+ "word": null,+ "words": [],+ "error": true+ },+ {+ "input": "hello\\\" there",+ "word": "hello\" there",+ "words": [+ "hello\"",+ "there"+ ]+ },+ {+ "input": "hello\"\\\\there\"",+ "word": "hello\"\\there\"",+ "words": [+ "hello\"\\there\""+ ]+ },+ {+ "input": "hello\"\\there\"",+ "word": "hello\"\\there\"",+ "words": [+ "hello\"\\there\""+ ]+ },+ {+ "input": "hello'\\\\there'",+ "word": "hello'\\\\there'",+ "words": [+ "hello'\\\\there'"+ ]+ },+ {+ "input": "hello'\\there'",+ "word": "hello'\\there'",+ "words": [+ "hello'\\there'"+ ]+ },+ {+ "input": "hello'$there'",+ "word": "hello'$there'",+ "words": [+ "hello'$there'"+ ]+ }+]diff --git a/packages/dockerfile-utils-python/tests/test_buildkit_parser.py b/packages/dockerfile-utils-python/tests/test_buildkit_parser.pynew file mode 100644index 000000000..c27c91c5b--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_buildkit_parser.py@@ -0,0 +1,437 @@+import unicodedata+from pathlib import Path+from typing import List++import pytest++from e2b_dockerfile_utils import (+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileSyntaxError,+ chomp_heredoc_content,+ parse_dockerfile_ast,+ parse_heredoc,+ parse_words,+)++# Port of BuildKit's `frontend/dockerfile/parser` tests, see+# `fixtures/buildkit/README.md`.++FIXTURES = Path(__file__).parent / "fixtures" / "buildkit" / "parser"++_GO_ESCAPES = {+ '"': '\\"',+ "\\": "\\\\",+ "\a": "\\a",+ "\b": "\\b",+ "\f": "\\f",+ "\n": "\\n",+ "\r": "\\r",+ "\t": "\\t",+ "\v": "\\v",+}+++def go_quote(s: str) -> str:+ """`strconv.Quote`"""+ out = '"'+ for ch in s:+ if ch in _GO_ESCAPES:+ out += _GO_ESCAPES[ch]+ elif ch == " " or unicodedata.category(ch)[0] in "LMNPS":+ out += ch+ else:+ cp = ord(ch)+ if cp < 0x80:+ out += f"\\x{cp:02x}"+ elif cp < 0x10000:+ out += f"\\u{cp:04x}"+ else:+ out += f"\\U{cp:08x}"+ return out + '"'+++def dump(instruction: DockerfileInstruction) -> str:+ """The flat equivalent of BuildKit's `Node.Dump()`"""+ text = instruction.name.lower()+ if instruction.flags:+ text += " [" + " ".join(go_quote(f) for f in instruction.flags) + "]"+ if instruction.name == "ONBUILD":+ # BuildKit parses the trigger as a child node+ rest = instruction.original.split(None, 1)[1]+ child = parse_dockerfile_ast(rest).instructions[0]+ return f"({text} {dump(child)})"+ for arg in instruction.args:+ text += " " + go_quote(arg)+ return f"({text})"+++def dump_all(content: str) -> str:+ return "\n".join(dump(i) for i in parse_dockerfile_ast(content).instructions)+++def read(*parts: str) -> str:+ return FIXTURES.joinpath(*parts).read_text(encoding="utf-8")+++# BuildKit splits shell-form ADD/COPY on whitespace only, this parser honors+# quotes so `COPY "a b" /dst` works, which changes the result for the+# unbalanced `ADD \\conf\\\\" /.znc`+_DEVIATIONS = {"escapes"}+++ "case", sorted(p.name for p in (FIXTURES / "testfiles").iterdir())+)+def test_parse_cases(case: str):+ if case in _DEVIATIONS:+ pytest.skip("ADD/COPY words are quote-aware here")+ dockerfile = read("testfiles", case, "Dockerfile")+ expected = read("testfiles", case, "result")+ assert dump_all(dockerfile) == expected.strip()+++# BuildKit reports "file with no instructions" for these; an empty instruction+# list is returned here instead+_EMPTY = {"empty_dockerfile", "only_comments"}+++ "case", sorted(p.name for p in (FIXTURES / "testfiles-negative").iterdir())+)+def test_parse_error_cases(case: str):+ dockerfile = read("testfiles-negative", case, "Dockerfile")+ if case in _EMPTY:+ assert parse_dockerfile_ast(dockerfile).instructions == []+ return+ with pytest.raises(DockerfileSyntaxError):+ parse_dockerfile_ast(dockerfile)+++def test_parse_includes_line_numbers():+ instructions = parse_dockerfile_ast(+ read("testfile-line", "Dockerfile")+ ).instructions+ assert [(i.start_line, i.end_line) for i in instructions] == [+ (5, 5),+ (11, 12),+ (17, 31),+ ]+++def test_parse_warns_on_empty_continuation_line():+ dockerfile = """+FROM alpine:3.6++RUN valid \\+ continuation++RUN something \\++ following \\++ more++RUN another \\++ thing++RUN non-indented \\+# this is a comment+ after-comment++RUN indented \\+ # this is an indented comment+ comment+\t"""+ warnings = parse_dockerfile_ast(dockerfile).warnings+ assert len(warnings) == 2+ assert "Empty continuation line found in" in warnings[0].message+ assert "RUN something following more" in warnings[0].message+ assert "RUN another thing" in warnings[1].message+++ ("line", "expected"),+ [+ ("foo", ["foo"]),+ ("foo bar", ["foo", "bar"]),+ ("foo\\ bar", ["foo\\ bar"]),+ ("foo=bar", ["foo=bar"]),+ ("foo bar 'abc xyz'", ["foo", "bar", "'abc xyz'"]),+ ('foo bar "abc xyz"', ["foo", "bar", '"abc xyz"']),+ ("àöû", ["àöû"]),+ ('föo bàr "âbc xÿz"', ["föo", "bàr", '"âbc xÿz"']),+ ],+)+def test_parse_words(line: str, expected: List[str]):+ assert parse_words(line, "\\") == expected+++ ("json_text", "expected"),+ [+ ("[]", []),+ ('[""]', [""]),+ ('["a"]', ["a"]),+ ('["a","b"]', ["a", "b"]),+ ('[ "a", "b" ]', ["a", "b"]),+ ('[\t"a",\t"b"\t]', ["a", "b"]),+ ('\t[\t"a",\t"b"\t]\t', ["a", "b"]),+ (+ '["abc 123", "♥", "☃", "\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u0000"]',+ ["abc 123", "♥", "☃", '" \\ / \b \f \n \r \t \u0000'],+ ),+ ],+)+def test_json_arrays_of_strings(json_text: str, expected: List[str]):+ run = parse_dockerfile_ast(f"RUN {json_text}").instructions[0]+ assert run.json is True+ assert run.args == expected+++ "json_text",+ [+ '["a",42,"b"]',+ '["a",123.456,"b"]',+ '["a",{},"b"]',+ '["a",{"c": "d"},"b"]',+ '["a",["c"],"b"]',+ '["a",true,"b"]',+ '["a",false,"b"]',+ '["a",null,"b"]',+ ],+)+def test_json_arrays_of_strings_invalid(json_text: str):+ with pytest.raises(+ DockerfileSyntaxError, match="Only strings are supported in JSON arrays"+ ):+ parse_dockerfile_ast(f"RUN {json_text}")+++def test_parse_name_val_old_format():+ label = parse_dockerfile_ast("LABEL foo bar").instructions[0]+ assert label.args == ["foo", "bar", ""]+++def test_parse_name_val_new_format():+ label = parse_dockerfile_ast("LABEL foo=bar thing=star").instructions[0]+ assert label.args == ["foo", "bar", "=", "thing", "star", "="]+++def test_parse_name_val_without_val():+ with pytest.raises(DockerfileSyntaxError, match="ENV must have two arguments"):+ parse_dockerfile_ast("ENV foo")+++def _heredoc(+ name: str,+ content: str,+ chomp: bool = False,+ expand: bool = True,+ file_descriptor: int = 0,+) -> DockerfileHeredoc:+ return DockerfileHeredoc(+ name=name,+ content=content,+ chomp=chomp,+ expand=expand,+ file_descriptor=file_descriptor,+ )+++def test_parse_extracts_heredoc():+ # The upstream file has an `INVALID` line after `USER <<INVALID`, which+ # this parser rejects as an unknown instruction+ dockerfile = """+FROM alpine:3.6+ENV NAME=me+RUN ls+USER <<INVALID+RUN <<EMPTY+EMPTY+RUN 3<<EMPTY2+EMPTY2+RUN "<<NOHEREDOC"+RUN <<INDENT+\tfoo+\tbar+INDENT+RUN <<-UNINDENT+\tbaz+\tquux+UNINDENT+RUN <<-UNINDENT2+\tbaz+\tquux+\tUNINDENT2+RUN <<-EXPAND+\texpand $NAME+EXPAND+RUN <<-'NOEXPAND'+\tdon't expand $NAME+NOEXPAND+RUN <<COPY+echo hello world+echo foo bar+COPY+RUN <<COMMENT+# internal comment+echo hello world+echo foo bar # trailing comment+COMMENT+RUN --mount=type=cache,target=/foo <<MOUNT+echo hello+MOUNT+COPY <<FILE1 <<FILE2 /dest+content 1+FILE1+content 2+FILE2+COPY <<EOF /quotes+"foo"+'bar'+EOF+COPY <<X <<Y /dest+Y+X+X+Y+RUN <<COMPLEX python3+print('hello world')+COMPLEX+COPY <<file.txt /dest+hello world+file.txt+RUN <<eo'f'+echo foo+eof+RUN <<eo\\'f+echo foo+eo'f+RUN <<'e'o\\'f+echo foo+eo'f+RUN <<'one two'+echo bar+one two+RUN <<$EOF+$EOF+RUN << EOF+EOF+RUN << EOF > foo+EOF+\t"""+ tests: List[List[DockerfileHeredoc]] = [+ [], # ENV EXAMPLE=bla+ [], # RUN ls+ [], # USER <<INVALID+ [_heredoc("EMPTY", "")],+ [_heredoc("EMPTY2", "", file_descriptor=3)],+ [], # RUN "<<NOHEREDOC"+ [_heredoc("INDENT", "\tfoo\n\tbar\n")],+ [_heredoc("UNINDENT", "\tbaz\n\tquux\n", chomp=True)],+ [_heredoc("UNINDENT2", "\tbaz\n\tquux\n", chomp=True)],+ [_heredoc("EXPAND", "\texpand $NAME\n", chomp=True)],+ [_heredoc("NOEXPAND", "\tdon't expand $NAME\n", chomp=True, expand=False)],+ [_heredoc("COPY", "echo hello world\necho foo bar\n")],+ [+ _heredoc(+ "COMMENT",+ "# internal comment\necho hello world\necho foo bar # trailing comment\n",+ )+ ],+ [_heredoc("MOUNT", "echo hello\n")],+ [_heredoc("FILE1", "content 1\n"), _heredoc("FILE2", "content 2\n")],+ [_heredoc("EOF", "\"foo\"\n'bar'\n")],+ [_heredoc("X", "Y\n"), _heredoc("Y", "X\n")],+ [_heredoc("COMPLEX", "print('hello world')\n")],+ [_heredoc("file.txt", "hello world\n")],+ [_heredoc("eof", "echo foo\n", expand=False)],+ [_heredoc("eo'f", "echo foo\n")],+ [_heredoc("eo'f", "echo foo\n", expand=False)],+ [_heredoc("one two", "echo bar\n", expand=False)],+ [_heredoc("$EOF", "")],+ [_heredoc("EOF", "")],+ [_heredoc("EOF", "")],+ ]+ instructions = parse_dockerfile_ast(dockerfile).instructions+ assert len(instructions) == len(tests) + 1+ for i, expected in enumerate(tests):+ assert instructions[i + 1].heredocs == expected+++def test_parse_json_heredoc():+ dockerfile = """+FROM alpine:3.6+RUN ["whoami"]+RUN ["<<EOF"]+RUN ["<<'EOF'"]+\t"""+ instructions = parse_dockerfile_ast(dockerfile).instructions+ for i in range(1, 4):+ assert instructions[i].heredocs == []+++def test_heredoc_chomp():+ assert chomp_heredoc_content("\thello\n\tworld\n") == "hello\nworld\n"+++def test_parse_heredoc_helpers():+ valid_heredocs = [+ "<<EOF",+ "<<'EOF'",+ '<<"EOF"',+ "<<-EOF",+ "<<-'EOF'",+ '<<-"EOF"',+ '<<EO"F"',+ "<< EOF",+ "<<- EOF",+ ]+ invalid_heredocs = ["<<'EOF", '<<"EOF', "<<EOF'", '<<EOF"']+ not_heredocs = ["", "EOF", "<<", "<<-", "<EOF", "<<<EOF", "<<EOF sh"]++ for src in not_heredocs:+ assert parse_heredoc(src) is None, src+ for src in valid_heredocs:+ heredoc = parse_heredoc(src)+ assert heredoc is not None and heredoc.name == "EOF", src+ for src in invalid_heredocs:+ with pytest.raises(ValueError):+ parse_heredoc(src)+++ ("line", "names"),+ [+ ("RUN <<EOF", ["EOF"]),+ ("RUN <<-EOF", ["EOF"]),+ ("RUN <<EOF", ["EOF"]),+ # upstream expects `EOF` here, but only asserts over the heredocs that+ # were found and BuildKit's lexer splits `<<-` and `EOF` into two words+ ("RUN <<- EOF", []),+ ("RUN << -EOF", ["-EOF"]),+ ("RUN <<'EOF'", ["EOF"]),+ ("RUN 4<<EOF", ["EOF"]),+ ("RUN <<EOF <<EOF2", ["EOF", "EOF2"]),+ ("RUN '<<EOF'", []),+ ('RUN "<<EOF"', []),+ ],+)+def test_heredocs_from_line(line: str, names: List[str]):+ dockerfile = "\n".join([line, *names, ""])+ run = parse_dockerfile_ast(dockerfile).instructions[0]+ assert [h.name for h in run.heredocs] == names+++ ("dockerfile", "escape_token"),+ [+ ("#escape=\\\n# key = FOO bar\nFROM x", "\\"),+ ("# EScape=`\nFROM x", "`"),+ ],+)+def test_directives(dockerfile: str, escape_token: str):+ assert parse_dockerfile_ast(dockerfile).escape_token == escape_tokendiff --git a/packages/dockerfile-utils-python/tests/test_buildkit_shell.py b/packages/dockerfile-utils-python/tests/test_buildkit_shell.pynew file mode 100644index 000000000..005c63c64--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_buildkit_shell.py@@ -0,0 +1,141 @@+import json+from pathlib import Path+from typing import Dict, List, Optional, TypedDict++import pytest++from e2b_dockerfile_utils import ShellLex++# BuildKit's `frontend/dockerfile/shell` word tables, see+# `fixtures/buildkit/README.md` for how the expectations were generated.++FIXTURES = Path(__file__).parent / "fixtures" / "buildkit" / "shell"+++class LexCase(TypedDict, total=False):+ input: str+ word: Optional[str]+ words: List[str]+ error: bool+++class EnvCase(TypedDict, total=False):+ input: str+ env: Dict[str, str]+ word: str+ words: List[str]+ error: bool+++def load_cases(name: str) -> List[LexCase]:+ return json.loads((FIXTURES / f"{name}.json").read_text(encoding="utf-8"))+++def check(case: LexCase, raw_quotes: bool) -> None:+ lex = ShellLex("\\", raw_quotes=raw_quotes)+ if case.get("error"):+ with pytest.raises(ValueError):+ lex.process_word(case["input"])+ with pytest.raises(ValueError):+ lex.process_words(case["input"])+ return+ assert lex.process_word(case["input"]) == case["word"]+ assert lex.process_words(case["input"]) == case["words"]++[email protected]("case", load_cases("wordsTest"), ids=lambda c: c["input"])+def test_words(case: LexCase):+ check(case, raw_quotes=False)+++ "case", load_cases("wordsTest.rawQuotes"), ids=lambda c: c["input"]+)+def test_words_raw_quotes(case: LexCase):+ check(case, raw_quotes=True)++[email protected]("case", load_cases("envVarTest"), ids=lambda c: c["input"])+def test_env_var(case: LexCase):+ check(case, raw_quotes=False)+++_ENV = {"PWD": "/home", "SHELL": "bash", "KOREAN": "한국어", "NULL": ""}++[email protected]("case", load_cases("envVarTest.env"), ids=lambda c: c["input"])+def test_env_var_expanded(case: LexCase):+ lex = ShellLex("\\", env=_ENV, skip_unset_env=False)+ if case.get("error"):+ with pytest.raises(ValueError):+ lex.process_word(case["input"])+ return+ assert lex.process_word(case["input"]) == case["word"]+++# TestShellParser4Words with the `ENV` lines of `wordsTest` applied+# cumulatively. Upstream also loops a RawQuotes + SkipUnsetEnv mode, but it+# re-scans the already exhausted file, so only the normal mode is asserted.[email protected]("case", load_cases("wordsTest.env"), ids=lambda c: c["input"])+def test_words_with_env(case: EnvCase):+ lex = ShellLex("\\", env=case["env"], skip_unset_env=False)+ if case.get("error"):+ with pytest.raises(ValueError):+ lex.process_words(case["input"])+ return+ assert lex.process_words(case["input"]) == case["words"]+++ "case", load_cases("processWithMatches"), ids=lambda c: c["input"]+)+def test_process_with_matches(case: EnvCase):+ lex = ShellLex("\\", env=case["env"], skip_unset_env=False)+ if case.get("error"):+ with pytest.raises(ValueError):+ lex.process_word(case["input"])+ return+ assert lex.process_word(case["input"]) == case["word"]+++def _expand(word: str, env: Dict[str, str]) -> str:+ return ShellLex("\\", env=env, skip_unset_env=False).process_word(word)+++def test_process_with_matches_platform():+ release = (+ "something-${VERSION}.${TARGETOS}-${TARGETARCH}"+ "${TARGETVARIANT:+-${TARGETVARIANT}}.tar.gz"+ )+ base = {"VERSION": "v1.2.3", "TARGETOS": "linux"}+ assert (+ _expand(release, {**base, "TARGETARCH": "arm", "TARGETVARIANT": "v7"})+ == "something-v1.2.3.linux-arm-v7.tar.gz"+ )+ assert (+ _expand(release, {**base, "TARGETARCH": "arm64", "TARGETVARIANT": ""})+ == "something-v1.2.3.linux-arm64.tar.gz"+ )+ assert (+ _expand(release, {**base, "TARGETARCH": "arm64"})+ == "something-v1.2.3.linux-arm64.tar.gz"+ )+++def test_shell_parser_mandatory_env_vars():+ set_ = {"VAR": "plain", "ARG": "x"}+ empty = {"VAR": "", "ARG": "x"}+ unset = {"ARG": "x"}+ no_empty = "${VAR:?message here$ARG}"+ no_unset = "${VAR?message here$ARG}"++ assert _expand(no_empty, set_) == "plain"+ with pytest.raises(ValueError, match="message herex"):+ _expand(no_empty, empty)+ with pytest.raises(ValueError, match="message herex"):+ _expand(no_empty, unset)++ assert _expand(no_unset, set_) == "plain"+ assert _expand(no_unset, empty) == ""+ with pytest.raises(ValueError, match="message herex"):+ _expand(no_unset, unset)diff --git a/packages/dockerfile-utils-python/tests/test_dockerignore.py b/packages/dockerfile-utils-python/tests/test_dockerignore.pynew file mode 100644index 000000000..4bed4766a--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_dockerignore.py@@ -0,0 +1,74 @@+import pytest++from e2b_dockerfile_utils import PatternMatcher+++def test_matches_like_dockerignore():+ matcher = PatternMatcher(+ [+ "# comment",+ "",+ "node_modules",+ "/dist/",+ "*.log",+ "**/*.tmp",+ "docs/**",+ "!docs/README.md",+ "src/[a-c]?.py",+ ]+ )++ assert matcher.matches("node_modules")+ assert matcher.matches("node_modules/pkg/index.js")+ assert not matcher.matches("src/node_modules")+ assert matcher.matches("dist")+ assert matcher.matches("dist/index.js")+ assert matcher.matches("app.log")+ assert not matcher.matches("logs/app.log")+ assert matcher.matches("a/b/c.tmp")+ assert matcher.matches("docs/guide/intro.md")+ assert not matcher.matches("docs/README.md")+ assert not matcher.matches("docs")+ assert matcher.matches("src/a1.py")+ assert not matcher.matches("src/d1.py")+ assert not matcher.matches("src/index.py")+++def test_parent_match_excludes_everything_under_it():+ matcher = PatternMatcher(["build", "!build/keep"])+ assert matcher.matches("build/out.js")+ assert not matcher.matches("build/keep")+ assert not matcher.matches("build/keep/file")+++def test_may_match_under():+ matcher = PatternMatcher(["*", "!src/lib/**", "!a/b/c"])+ assert matcher.may_match_under("src")+ assert matcher.may_match_under("src/lib")+ assert matcher.may_match_under("a/b")+ assert not matcher.may_match_under("a/b/c")+ assert not matcher.may_match_under("other")+++def test_cleans_patterns():+ matcher = PatternMatcher(["./a//b/", "c/./d/../e", "/f/", "../g", "/../h"])+ assert matcher.matches("a/b")+ assert matcher.matches("c/e")+ assert matcher.matches("f/x")+ assert matcher.matches("../g")+ assert matcher.matches("h")+++def test_backslash_handling():+ assert PatternMatcher(["a\\*b"]).matches("a*b")+ assert not PatternMatcher(["a\\*b"]).matches("a/b")+ windows = PatternMatcher(["a\\*b", "c\\d"], backslash_is_separator=True)+ assert windows.matches("a/xb")+ assert windows.matches("c/d/e")+++def test_rejects_invalid_patterns_with_value_error():+ with pytest.raises(ValueError, match=r"Invalid ignore pattern '\[abc'"):+ PatternMatcher(["[abc"])+ with pytest.raises(ValueError, match=r"Invalid ignore pattern '\[\\q\]'"):+ PatternMatcher(["[\\q]"])diff --git a/packages/dockerfile-utils-python/tests/test_lexer.py b/packages/dockerfile-utils-python/tests/test_lexer.pynew file mode 100644index 000000000..23d699a02--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_lexer.py@@ -0,0 +1,61 @@+import pytest++from e2b_dockerfile_utils import ShellLex, is_space++lex = ShellLex("\\")+++def test_splits_words_and_strips_quotes():+ assert lex.process_words('KEY="a b" OTHER=c') == ["KEY=a b", "OTHER=c"]+ assert lex.process_words('a "b c" d\\ e') == ["a", "b c", "d e"]+++def test_preserves_variable_references():+ assert lex.process_words('"$HOME"/x') == ["$HOME/x"]+ assert lex.process_words("'$HOME'") == ["$HOME"]+ assert lex.process_words("${V//a/b}") == ["${V//a/b}"]+ assert lex.process_words("a\\$b") == ["a$b"]+++def test_expands_variables_from_env():+ env = {"V": "a/b/c", "E": ""}+ lex = ShellLex("\\", env=env)+ assert lex.process_word('$V-${V}-"$V"') == "a/b/c-a/b/c-a/b/c"+ assert lex.process_word("${V:-x}${E:-x}${E-x}${U:-x}") == "a/b/cx${U:-x}"+ assert lex.process_word("${V:+y}${E:+y}${E+y}${U+y}") == "yy${U+y}"+ assert lex.process_word("${V:?}${U:?msg}") == "a/b/c${U:?msg}"+ with pytest.raises(ValueError, match="E: empty"):+ lex.process_word("${E:?empty}")+ assert lex.process_word("${V#*/} ${V##*/}") == "b/c c"+ assert lex.process_word("${V%/*} ${V%%/*}") == "a/b a"+ assert lex.process_word("${V/b/x} ${V//\\//-} ${V/?/x}") == "a/x/c a-b-c x/b/c"+ assert lex.process_word("$U ${U} ${U/a/b}") == "$U ${U} ${U/a/b}"+ assert (+ ShellLex("\\", env=env, skip_unset_env=False).process_word("$U-${U:-d}") == "-d"+ )+++def test_keeps_heredoc_markers_intact():+ assert lex.process_words("<<EOF cat") == ["<<EOF", "cat"]+++def test_honours_the_escape_token():+ assert ShellLex("`").process_word('a`"b') == 'a"b'+++def test_raw_modes_keep_quotes_and_escapes():+ assert ShellLex("\\", raw_quotes=True).process_word('"a b"') == '"a b"'+ assert ShellLex("\\", raw_escapes=True).process_word('a\\"b') == 'a\\"b'+++def test_rejects_unterminated_quotes():+ with pytest.raises(ValueError, match="double-quote"):+ lex.process_word('"unterminated')+ with pytest.raises(ValueError, match="single-quote"):+ lex.process_word("x 'y")+++def test_is_space():+ assert is_space(" ")+ assert is_space("\xa0")+ assert not is_space("a")diff --git a/packages/dockerfile-utils-python/tests/test_moby_patternmatcher.py b/packages/dockerfile-utils-python/tests/test_moby_patternmatcher.pynew file mode 100644index 000000000..a1ebfe286--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_moby_patternmatcher.py@@ -0,0 +1,318 @@+import pytest++from e2b_dockerfile_utils import PatternMatcher++# Port of moby/patternmatcher v0.6.1 `patternmatcher_test.go` and+# `ignorefile/ignorefile_test.go`. `Matches`, `MatchesOrParentMatches`,+# `MatchesUsingParentResult(s)` all map to `PatternMatcher.matches`.+++def matches(text: str, patterns: list[str]) -> bool:+ return PatternMatcher(patterns).matches(text)+++# (pattern, text, pass)+MATCHES_TESTS = [+ ("**", "file", True),+ ("**", "file/", True),+ ("**/", "file", True), # weird one+ ("**/", "file/", True),+ ("**", "/", True),+ ("**/", "/", True),+ ("**", "dir/file", True),+ ("**/", "dir/file", True),+ ("**", "dir/file/", True),+ ("**/", "dir/file/", True),+ ("**/**", "dir/file", True),+ ("**/**", "dir/file/", True),+ ("dir/**", "dir/file", True),+ ("dir/**", "dir/file/", True),+ ("dir/**", "dir/dir2/file", True),+ ("dir/**", "dir/dir2/file/", True),+ ("**/dir", "dir", True),+ ("**/dir", "dir/file", True),+ ("**/dir2/*", "dir/dir2/file", True),+ ("**/dir2/*", "dir/dir2/file/", True),+ ("**/dir2/**", "dir/dir2/dir3/file", True),+ ("**/dir2/**", "dir/dir2/dir3/file/", True),+ ("**file", "file", True),+ ("**file", "dir/file", True),+ ("**/file", "dir/file", True),+ ("**file", "dir/dir/file", True),+ ("**/file", "dir/dir/file", True),+ ("**/file*", "dir/dir/file", True),+ ("**/file*", "dir/dir/file.txt", True),+ ("**/file*txt", "dir/dir/file.txt", True),+ ("**/file*.txt", "dir/dir/file.txt", True),+ ("**/file*.txt*", "dir/dir/file.txt", True),+ ("**/**/*.txt", "dir/dir/file.txt", True),+ ("**/**/*.txt2", "dir/dir/file.txt", False),+ ("**/*.txt", "file.txt", True),+ ("**/**/*.txt", "file.txt", True),+ ("a**/*.txt", "a/file.txt", True),+ ("a**/*.txt", "a/dir/file.txt", True),+ ("a**/*.txt", "a/dir/dir/file.txt", True),+ ("a/*.txt", "a/dir/file.txt", False),+ ("a/*.txt", "a/file.txt", True),+ ("a/*.txt**", "a/file.txt", True),+ ("a[b-d]e", "ae", False),+ ("a[b-d]e", "ace", True),+ ("a[b-d]e", "aae", False),+ ("a[^b-d]e", "aze", True),+ (".*", ".foo", True),+ (".*", "foo", False),+ ("abc.def", "abcdef", False),+ ("abc.def", "abc.def", True),+ ("abc.def", "abcZdef", False),+ ("abc?def", "abcZdef", True),+ ("abc?def", "abcdef", False),+ ("a\\\\", "a\\", True),+ ("**/foo/bar", "foo/bar", True),+ ("**/foo/bar", "dir/foo/bar", True),+ ("**/foo/bar", "dir/dir2/foo/bar", True),+ ("abc/**", "abc", False),+ ("abc/**", "abc/def", True),+ ("abc/**", "abc/def/ghi", True),+ ("**/.foo", ".foo", True),+ ("**/.foo", "bar.foo", False),+ ("a(b)c/def", "a(b)c/def", True),+ ("a(b)c/def", "a(b)c/xyz", False),+ ("a.|)$(}+{bc", "a.|)$(}+{bc", True),+ (+ "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl",+ "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl",+ True,+ ),+ ("dist/*.whl", "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl", True),+ # non-windows only upstream+ ("a\\*b", "a*b", True),+]++# (patterns, text, pass)+MULTI_PATTERN_TESTS = [+ (["**", "!util/docker/web"], "util/docker/web/foo", False),+ (["**", "!util/docker/web", "util/docker/web/foo"], "util/docker/web/foo", True),+ (+ ["**", "!dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl"],+ "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl",+ False,+ ),+ (+ ["**", "!dist/*.whl"],+ "dist/proxy.py-2.4.0rc3.dev36+g08acad9-py3-none-any.whl",+ False,+ ),+]++# (pattern, s, match, bad pattern)+MATCH_TESTS = [+ ("abc", "abc", True, False),+ ("*", "abc", True, False),+ ("*c", "abc", True, False),+ ("a*", "a", True, False),+ ("a*", "abc", True, False),+ ("a*", "ab/c", True, False),+ ("a*/b", "abc/b", True, False),+ ("a*/b", "a/c/b", False, False),+ ("a*b*c*d*e*/f", "axbxcxdxe/f", True, False),+ ("a*b*c*d*e*/f", "axbxcxdxexxx/f", True, False),+ ("a*b*c*d*e*/f", "axbxcxdxe/xxx/f", False, False),+ ("a*b*c*d*e*/f", "axbxcxdxexxx/fff", False, False),+ ("a*b?c*x", "abxbbxdbxebxczzx", True, False),+ ("a*b?c*x", "abxbbxdbxebxczzy", False, False),+ ("ab[c]", "abc", True, False),+ ("ab[b-d]", "abc", True, False),+ ("ab[e-g]", "abc", False, False),+ ("ab[^c]", "abc", False, False),+ ("ab[^b-d]", "abc", False, False),+ ("ab[^e-g]", "abc", True, False),+ ("a\\*b", "a*b", True, False),+ ("a\\*b", "ab", False, False),+ ("a?b", "a☺b", True, False),+ ("a[^a]b", "a☺b", True, False),+ ("a???b", "a☺b", False, False),+ ("a[^a][^a][^a]b", "a☺b", False, False),+ ("[a-ζ]*", "α", True, False),+ ("*[a-ζ]", "A", False, False),+ ("a?b", "a/b", False, False),+ ("a*b", "a/b", False, False),+ ("[\\]a]", "]", True, False),+ ("[\\-]", "-", True, False),+ ("[x\\-]", "x", True, False),+ ("[x\\-]", "-", True, False),+ ("[x\\-]", "z", False, False),+ ("[\\-x]", "x", True, False),+ ("[\\-x]", "-", True, False),+ ("[\\-x]", "a", False, False),+ ("[]a]", "]", False, True),+ ("[-]", "-", False, True),+ ("[x-]", "x", False, True),+ ("[x-]", "-", False, True),+ ("[x-]", "z", False, True),+ ("[-x]", "x", False, True),+ ("[-x]", "-", False, True),+ ("[-x]", "a", False, True),+ ("\\", "a", False, True),+ ("[a-b-c]", "a", False, True),+ ("[", "a", False, True),+ ("[^", "a", False, True),+ ("[^bc", "a", False, True),+ ("a[", "a", False, True),+ ("a[", "ab", False, True),+ ("*x", "xxx", True, False),+]+++def test_wildcard_matches():+ assert matches("fileutils.go", ["*"])+++def test_pattern_matches():+ assert matches("fileutils.go", ["*.go"])+++def test_exclusion_pattern_matches_pattern_before():+ assert matches("fileutils.go", ["!fileutils.go", "*.go"])+++def test_pattern_matches_folder_exclusions():+ assert not matches("docs/README.md", ["docs", "!docs/README.md"])+++def test_pattern_matches_folder_with_slash_exclusions():+ assert not matches("docs/README.md", ["docs/", "!docs/README.md"])+++def test_pattern_matches_folder_wildcard_exclusions():+ assert not matches("docs/README.md", ["docs/*", "!docs/README.md"])+++def test_exclusion_pattern_matches_pattern_after():+ assert not matches("fileutils.go", ["*.go", "!fileutils.go"])+++def test_exclusion_pattern_matches_whole_directory():+ assert not matches(".", ["*.go"])+++def test_single_exclamation_error():+ with pytest.raises(ValueError, match="illegal exclusion"):+ matches("fileutils.go", ["!"])+++def test_matches_with_no_patterns():+ assert not matches("/any/path/there", [])+++def test_matches_with_malformed_patterns():+ with pytest.raises(ValueError):+ matches("/any/path/there", ["["])++[email protected](("pattern", "text", "expected"), MATCHES_TESTS)+def test_matches(pattern: str, text: str, expected: bool):+ assert matches(text, [pattern]) is expected++[email protected](("patterns", "text", "expected"), MULTI_PATTERN_TESTS)+def test_matches_multi_pattern(patterns: list[str], text: str, expected: bool):+ assert matches(text, patterns) is expected+++# Upstream runs the same table on Windows, where `filepath.Clean` turns the+# slashes into backslashes+ ("pattern", "text", "expected"),+ [case for case in MATCHES_TESTS if "\\" not in case[0]],+)+def test_matches_windows(pattern: str, text: str, expected: bool):+ matcher = PatternMatcher([pattern.replace("/", "\\")], backslash_is_separator=True)+ assert matcher.matches(text.replace("/", "\\")) is expected+++def test_clean_patterns():+ assert len(PatternMatcher(["docs", "config"]).patterns) == 2+++def test_clean_patterns_strip_empty_patterns():+ assert len(PatternMatcher(["docs", "config", ""]).patterns) == 2+++def test_clean_patterns_exception_flag():+ matcher = PatternMatcher(["docs", "!docs/README.md"])+ assert matcher.patterns == ["docs", "!docs/README.md"]+++def test_clean_patterns_leading_space_trimmed():+ matcher = PatternMatcher(["docs", " !docs/README.md"])+ assert matcher.patterns == ["docs", "!docs/README.md"]+++def test_clean_patterns_trailing_space_trimmed():+ matcher = PatternMatcher(["docs", "!docs/README.md "])+ assert matcher.patterns == ["docs", "!docs/README.md"]+++def test_clean_patterns_error_single_exception():+ with pytest.raises(ValueError, match="illegal exclusion"):+ PatternMatcher(["!"])++[email protected](("pattern", "s", "expected", "bad"), MATCH_TESTS)+def test_match(pattern: str, s: str, expected: bool, bad: bool):+ if bad:+ with pytest.raises(ValueError, match="syntax error"):+ PatternMatcher([pattern])+ return+ assert matches(s, [pattern]) is expected+++# On Windows upstream skips the patterns containing backslashes+ ("pattern", "s", "expected", "bad"),+ [case for case in MATCH_TESTS if "\\" not in case[0]],+)+def test_match_windows(pattern: str, s: str, expected: bool, bad: bool):+ def create() -> PatternMatcher:+ return PatternMatcher([pattern.replace("/", "\\")], backslash_is_separator=True)++ if bad:+ with pytest.raises(ValueError, match="syntax error"):+ create()+ return+ assert create().matches(s.replace("/", "\\")) is expected+++def test_matches_or_parent_matches_malformed_pattern_does_not_panic_on_repeated_call():+ # Upstream only fails when matching; the patterns are compiled upfront+ # here so the bad range is reported when the matcher is created+ with pytest.raises(ValueError):+ PatternMatcher(["[Local-Only]/"])+ with pytest.raises(ValueError):+ PatternMatcher(["[Local-Only]/"])+++def test_ignorefile_read_all():+ content = [+ "test1",+ "/test2",+ "/a/file/here",+ "",+ "lastfile",+ "# this is a comment",+ " # not a comment",+ "! /inverted/abs/path",+ ]+ assert PatternMatcher(content).patterns == [+ "test1",+ "test2",+ "a/file/here",+ "lastfile",+ "# not a comment",+ "!inverted/abs/path",+ ]+ # Upstream `ReadAll` keeps `!` and `! ` as `!`, which `New` then rejects+ with pytest.raises(ValueError):+ PatternMatcher([*content, "!"])+ with pytest.raises(ValueError):+ PatternMatcher([*content, "! "])diff --git a/packages/dockerfile-utils-python/tests/test_syntax.py b/packages/dockerfile-utils-python/tests/test_syntax.pynew file mode 100644index 000000000..bbbe41140--- /dev/null+++ b/packages/dockerfile-utils-python/tests/test_syntax.py@@ -0,0 +1,123 @@+import pytest++from e2b_dockerfile_utils import (+ DockerfileHeredoc,+ DockerfileSyntaxError,+ chomp_heredoc_content,+ parse_dockerfile_ast,+ parse_heredoc,+ parse_words,+)+++def test_upper_cases_instruction_names_and_keeps_argument_casing():+ ast = parse_dockerfile_ast("from node:24 as build\n")+ assert ast.escape_token == "\\"+ assert len(ast.instructions) == 1+ assert ast.instructions[0].name == "FROM"+ assert ast.instructions[0].args == ["node:24", "as", "build"]+ assert ast.instructions[0].json is False+++def test_honours_the_escape_directive():+ ast = parse_dockerfile_ast("# escape=`\nFROM a\nRUN echo a `\n b\n")+ assert ast.escape_token == "`"+ run = ast.instructions[1]+ assert run.args == ["echo a b"]+ assert run.start_line == 3+ assert run.end_line == 4+++def test_drops_comments_inside_continuations():+ ast = parse_dockerfile_ast(+ "FROM a\nRUN apt-get update \\\n # comment\n && apt-get install -y curl\n"+ )+ assert ast.instructions[1].args == ["apt-get update && apt-get install -y curl"]+++def test_parses_json_form():+ ast = parse_dockerfile_ast('FROM a\nCMD ["a", "b c"]\n')+ assert ast.instructions[1].json is True+ assert ast.instructions[1].args == ["a", "b c"]+++def test_separates_builder_flags_from_arguments():+ ast = parse_dockerfile_ast("FROM a\nCOPY --chown=1:1 --chmod=755 a b /d\n")+ assert ast.instructions[1].flags == ["--chown=1:1", "--chmod=755"]+ assert ast.instructions[1].args == ["a", "b", "/d"]+++def test_parses_env_key_value_and_legacy_forms_into_triples():+ ast = parse_dockerfile_ast('FROM a\nENV A=1 B="x y"\nENV LEGACY some value\n')+ assert ast.instructions[1].args == ["A", "1", "=", "B", '"x y"', "="]+ assert ast.instructions[2].args == ["LEGACY", "some value", ""]+++def test_collects_heredocs():+ ast = parse_dockerfile_ast(+ "FROM a\nRUN <<EOF\necho hi\nEOF\nRUN <<-'EOT' cat\n\thi\nEOT\n"+ )+ _, first, second = ast.instructions+ assert first.args == ["<<EOF"]+ assert first.heredocs == [+ DockerfileHeredoc(+ name="EOF", content="echo hi\n", chomp=False, expand=True, file_descriptor=0+ )+ ]+ assert first.end_line == 4+ assert second.heredocs == [+ DockerfileHeredoc(+ name="EOT", content="\thi\n", chomp=True, expand=False, file_descriptor=0+ )+ ]+++def test_strips_a_bom():+ ast = parse_dockerfile_ast("\ufeffFROM a\n")+ assert ast.instructions[0].name == "FROM"+++def test_warns_about_empty_continuation_lines():+ ast = parse_dockerfile_ast("FROM a\nRUN a \\\n\nb\n")+ assert ast.instructions[1].args == ["a b"]+ assert len(ast.warnings) == 1+ assert "Empty continuation line" in ast.warnings[0].message+++def test_tolerates_a_trailing_continuation_at_eof():+ ast = parse_dockerfile_ast("FROM a\nRUN echo \\\n")+ assert ast.instructions[1].args == ["echo"]+++def test_accepts_empty_and_comment_only_input():+ assert parse_dockerfile_ast("").instructions == []+ assert parse_dockerfile_ast("# only comment\n").instructions == []+++def test_rejects_unknown_instructions_with_a_line_number():+ with pytest.raises(DockerfileSyntaxError, match="line 2: unknown instruction: RNU"):+ parse_dockerfile_ast("FROM a\nRNU x\n")+++def test_parse_heredoc():+ assert parse_heredoc("<<" + " " * 50_000 + "<") is None+ assert parse_heredoc("<<" + " " * 50_000) is None+ assert parse_heredoc("\u00b2<<EOF") is None+ assert parse_heredoc("<<-EOF") == DockerfileHeredoc(+ name="EOF", content="", chomp=True, expand=True, file_descriptor=0+ )+ assert parse_heredoc("<<'EOF'") == DockerfileHeredoc(+ name="EOF", content="", chomp=False, expand=False, file_descriptor=0+ )+ heredoc = parse_heredoc("3<<EOF")+ assert heredoc is not None and heredoc.file_descriptor == 3+ assert parse_heredoc("<<") is None+ assert parse_heredoc("abc") is None+++def test_chomp_heredoc_content_strips_leading_tabs():+ assert chomp_heredoc_content("\thi\n\t\tthere\n") == "hi\nthere\n"+++def test_parse_words_keeps_quotes_and_escapes():+ assert parse_words('a "b c" d\\ e', "\\") == ["a", '"b c"', "d\\ e"]diff --git a/packages/dockerfile-utils-python/uv.lock b/packages/dockerfile-utils-python/uv.locknew file mode 100644index 000000000..12a42910b--- /dev/null+++ b/packages/dockerfile-utils-python/uv.lock@@ -0,0 +1,211 @@+version = 1+revision = 3+requires-python = ">=3.10"++[[package]]+name = "colorama"+version = "0.4.6"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },+]++[[package]]+name = "e2b-dockerfile-utils"+version = "0.0.0"+source = { editable = "." }++[package.dev-dependencies]+dev = [+ { name = "pytest" },+ { name = "ruff" },+ { name = "ty" },+]++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=9.0.3,<10" },+ { name = "ruff", specifier = ">=0.11.12,<0.12" },+ { name = "ty", specifier = ">=0.0.15,<0.0.16" },+]++[[package]]+name = "exceptiongroup"+version = "1.3.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },+]++[[package]]+name = "iniconfig"+version = "2.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },+]++[[package]]+name = "packaging"+version = "26.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },+]++[[package]]+name = "pluggy"+version = "1.6.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },+]++[[package]]+name = "pygments"+version = "2.21.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },+]++[[package]]+name = "pytest"+version = "9.1.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "colorama", marker = "sys_platform == 'win32'" },+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },+ { name = "iniconfig" },+ { name = "packaging" },+ { name = "pluggy" },+ { name = "pygments" },+ { name = "tomli", marker = "python_full_version < '3.11'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },+]++[[package]]+name = "ruff"+version = "0.11.13"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/ed/da/9c6f995903b4d9474b39da91d2d626659af3ff1eeb43e9ae7c119349dba6/ruff-0.11.13.tar.gz", hash = "sha256:26fa247dc68d1d4e72c179e08889a25ac0c7ba4d78aecfc835d49cbfd60bf514", size = 4282054, upload-time = "2025-06-05T21:00:15.721Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/7d/ce/a11d381192966e0b4290842cc8d4fac7dc9214ddf627c11c1afff87da29b/ruff-0.11.13-py3-none-linux_armv6l.whl", hash = "sha256:4bdfbf1240533f40042ec00c9e09a3aade6f8c10b6414cf11b519488d2635d46", size = 10292516, upload-time = "2025-06-05T20:59:32.944Z" },+ { url = "https://files.pythonhosted.org/packages/78/db/87c3b59b0d4e753e40b6a3b4a2642dfd1dcaefbff121ddc64d6c8b47ba00/ruff-0.11.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aef9c9ed1b5ca28bb15c7eac83b8670cf3b20b478195bd49c8d756ba0a36cf48", size = 11106083, upload-time = "2025-06-05T20:59:37.03Z" },+ { url = "https://files.pythonhosted.org/packages/77/79/d8cec175856ff810a19825d09ce700265f905c643c69f45d2b737e4a470a/ruff-0.11.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:53b15a9dfdce029c842e9a5aebc3855e9ab7771395979ff85b7c1dedb53ddc2b", size = 10436024, upload-time = "2025-06-05T20:59:39.741Z" },+ { url = "https://files.pythonhosted.org/packages/8b/5b/f6d94f2980fa1ee854b41568368a2e1252681b9238ab2895e133d303538f/ruff-0.11.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab153241400789138d13f362c43f7edecc0edfffce2afa6a68434000ecd8f69a", size = 10646324, upload-time = "2025-06-05T20:59:42.185Z" },+ { url = "https://files.pythonhosted.org/packages/6c/9c/b4c2acf24ea4426016d511dfdc787f4ce1ceb835f3c5fbdbcb32b1c63bda/ruff-0.11.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c51f93029d54a910d3d24f7dd0bb909e31b6cd989a5e4ac513f4eb41629f0dc", size = 10174416, upload-time = "2025-06-05T20:59:44.319Z" },+ { url = "https://files.pythonhosted.org/packages/f3/10/e2e62f77c65ede8cd032c2ca39c41f48feabedb6e282bfd6073d81bb671d/ruff-0.11.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1808b3ed53e1a777c2ef733aca9051dc9bf7c99b26ece15cb59a0320fbdbd629", size = 11724197, upload-time = "2025-06-05T20:59:46.935Z" },+ { url = "https://files.pythonhosted.org/packages/bb/f0/466fe8469b85c561e081d798c45f8a1d21e0b4a5ef795a1d7f1a9a9ec182/ruff-0.11.13-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:d28ce58b5ecf0f43c1b71edffabe6ed7f245d5336b17805803312ec9bc665933", size = 12511615, upload-time = "2025-06-05T20:59:49.534Z" },+ { url = "https://files.pythonhosted.org/packages/17/0e/cefe778b46dbd0cbcb03a839946c8f80a06f7968eb298aa4d1a4293f3448/ruff-0.11.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55e4bc3a77842da33c16d55b32c6cac1ec5fb0fbec9c8c513bdce76c4f922165", size = 12117080, upload-time = "2025-06-05T20:59:51.654Z" },+ { url = "https://files.pythonhosted.org/packages/5d/2c/caaeda564cbe103bed145ea557cb86795b18651b0f6b3ff6a10e84e5a33f/ruff-0.11.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:633bf2c6f35678c56ec73189ba6fa19ff1c5e4807a78bf60ef487b9dd272cc71", size = 11326315, upload-time = "2025-06-05T20:59:54.469Z" },+ { url = "https://files.pythonhosted.org/packages/75/f0/782e7d681d660eda8c536962920c41309e6dd4ebcea9a2714ed5127d44bd/ruff-0.11.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ffbc82d70424b275b089166310448051afdc6e914fdab90e08df66c43bb5ca9", size = 11555640, upload-time = "2025-06-05T20:59:56.986Z" },+ { url = "https://files.pythonhosted.org/packages/5d/d4/3d580c616316c7f07fb3c99dbecfe01fbaea7b6fd9a82b801e72e5de742a/ruff-0.11.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4a9ddd3ec62a9a89578c85842b836e4ac832d4a2e0bfaad3b02243f930ceafcc", size = 10507364, upload-time = "2025-06-05T20:59:59.154Z" },+ { url = "https://files.pythonhosted.org/packages/5a/dc/195e6f17d7b3ea6b12dc4f3e9de575db7983db187c378d44606e5d503319/ruff-0.11.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d237a496e0778d719efb05058c64d28b757c77824e04ffe8796c7436e26712b7", size = 10141462, upload-time = "2025-06-05T21:00:01.481Z" },+ { url = "https://files.pythonhosted.org/packages/f4/8e/39a094af6967faa57ecdeacb91bedfb232474ff8c3d20f16a5514e6b3534/ruff-0.11.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:26816a218ca6ef02142343fd24c70f7cd8c5aa6c203bca284407adf675984432", size = 11121028, upload-time = "2025-06-05T21:00:04.06Z" },+ { url = "https://files.pythonhosted.org/packages/5a/c0/b0b508193b0e8a1654ec683ebab18d309861f8bd64e3a2f9648b80d392cb/ruff-0.11.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:51c3f95abd9331dc5b87c47ac7f376db5616041173826dfd556cfe3d4977f492", size = 11602992, upload-time = "2025-06-05T21:00:06.249Z" },+ { url = "https://files.pythonhosted.org/packages/7c/91/263e33ab93ab09ca06ce4f8f8547a858cc198072f873ebc9be7466790bae/ruff-0.11.13-py3-none-win32.whl", hash = "sha256:96c27935418e4e8e77a26bb05962817f28b8ef3843a6c6cc49d8783b5507f250", size = 10474944, upload-time = "2025-06-05T21:00:08.459Z" },+ { url = "https://files.pythonhosted.org/packages/46/f4/7c27734ac2073aae8efb0119cae6931b6fb48017adf048fdf85c19337afc/ruff-0.11.13-py3-none-win_amd64.whl", hash = "sha256:29c3189895a8a6a657b7af4e97d330c8a3afd2c9c8f46c81e2fc5a31866517e3", size = 11548669, upload-time = "2025-06-05T21:00:11.147Z" },+ { url = "https://files.pythonhosted.org/packages/ec/bf/b273dd11673fed8a6bd46032c0ea2a04b2ac9bfa9c628756a5856ba113b0/ruff-0.11.13-py3-none-win_arm64.whl", hash = "sha256:b4385285e9179d608ff1d2fb9922062663c658605819a6876d8beef0c30b7f3b", size = 10683928, upload-time = "2025-06-05T21:00:13.758Z" },+]++[[package]]+name = "tomli"+version = "2.4.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f4/11/db3d5885d8528263d8adc260bb2d28ebf1270b96e98f0e0268d32b8d9900/tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30", size = 154704, upload-time = "2026-03-25T20:21:10.473Z" },+ { url = "https://files.pythonhosted.org/packages/6d/f7/675db52c7e46064a9aa928885a9b20f4124ecb9bc2e1ce74c9106648d202/tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a", size = 149454, upload-time = "2026-03-25T20:21:12.036Z" },+ { url = "https://files.pythonhosted.org/packages/61/71/81c50943cf953efa35bce7646caab3cf457a7d8c030b27cfb40d7235f9ee/tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076", size = 237561, upload-time = "2026-03-25T20:21:13.098Z" },+ { url = "https://files.pythonhosted.org/packages/48/c1/f41d9cb618acccca7df82aaf682f9b49013c9397212cb9f53219e3abac37/tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9", size = 243824, upload-time = "2026-03-25T20:21:14.569Z" },+ { url = "https://files.pythonhosted.org/packages/22/e4/5a816ecdd1f8ca51fb756ef684b90f2780afc52fc67f987e3c61d800a46d/tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c", size = 242227, upload-time = "2026-03-25T20:21:15.712Z" },+ { url = "https://files.pythonhosted.org/packages/6b/49/2b2a0ef529aa6eec245d25f0c703e020a73955ad7edf73e7f54ddc608aa5/tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc", size = 247859, upload-time = "2026-03-25T20:21:17.001Z" },+ { url = "https://files.pythonhosted.org/packages/83/bd/6c1a630eaca337e1e78c5903104f831bda934c426f9231429396ce3c3467/tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049", size = 97204, upload-time = "2026-03-25T20:21:18.079Z" },+ { url = "https://files.pythonhosted.org/packages/42/59/71461df1a885647e10b6bb7802d0b8e66480c61f3f43079e0dcd315b3954/tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e", size = 108084, upload-time = "2026-03-25T20:21:18.978Z" },+ { url = "https://files.pythonhosted.org/packages/b8/83/dceca96142499c069475b790e7913b1044c1a4337e700751f48ed723f883/tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece", size = 95285, upload-time = "2026-03-25T20:21:20.309Z" },+ { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" },+ { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" },+ { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" },+ { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" },+ { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" },+ { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" },+ { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" },+ { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" },+ { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" },+ { url = "https://files.pythonhosted.org/packages/07/06/b823a7e818c756d9a7123ba2cda7d07bc2dd32835648d1a7b7b7a05d848d/tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54", size = 155866, upload-time = "2026-03-25T20:21:31.65Z" },+ { url = "https://files.pythonhosted.org/packages/14/6f/12645cf7f08e1a20c7eb8c297c6f11d31c1b50f316a7e7e1e1de6e2e7b7e/tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a", size = 149887, upload-time = "2026-03-25T20:21:33.028Z" },+ { url = "https://files.pythonhosted.org/packages/5c/e0/90637574e5e7212c09099c67ad349b04ec4d6020324539297b634a0192b0/tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897", size = 243704, upload-time = "2026-03-25T20:21:34.51Z" },+ { url = "https://files.pythonhosted.org/packages/10/8f/d3ddb16c5a4befdf31a23307f72828686ab2096f068eaf56631e136c1fdd/tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f", size = 251628, upload-time = "2026-03-25T20:21:36.012Z" },+ { url = "https://files.pythonhosted.org/packages/e3/f1/dbeeb9116715abee2485bf0a12d07a8f31af94d71608c171c45f64c0469d/tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d", size = 247180, upload-time = "2026-03-25T20:21:37.136Z" },+ { url = "https://files.pythonhosted.org/packages/d3/74/16336ffd19ed4da28a70959f92f506233bd7cfc2332b20bdb01591e8b1d1/tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5", size = 251674, upload-time = "2026-03-25T20:21:38.298Z" },+ { url = "https://files.pythonhosted.org/packages/16/f9/229fa3434c590ddf6c0aa9af64d3af4b752540686cace29e6281e3458469/tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd", size = 97976, upload-time = "2026-03-25T20:21:39.316Z" },+ { url = "https://files.pythonhosted.org/packages/6a/1e/71dfd96bcc1c775420cb8befe7a9d35f2e5b1309798f009dca17b7708c1e/tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36", size = 108755, upload-time = "2026-03-25T20:21:40.248Z" },+ { url = "https://files.pythonhosted.org/packages/83/7a/d34f422a021d62420b78f5c538e5b102f62bea616d1d75a13f0a88acb04a/tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd", size = 95265, upload-time = "2026-03-25T20:21:41.219Z" },+ { url = "https://files.pythonhosted.org/packages/3c/fb/9a5c8d27dbab540869f7c1f8eb0abb3244189ce780ba9cd73f3770662072/tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf", size = 155726, upload-time = "2026-03-25T20:21:42.23Z" },+ { url = "https://files.pythonhosted.org/packages/62/05/d2f816630cc771ad836af54f5001f47a6f611d2d39535364f148b6a92d6b/tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac", size = 149859, upload-time = "2026-03-25T20:21:43.386Z" },+ { url = "https://files.pythonhosted.org/packages/ce/48/66341bdb858ad9bd0ceab5a86f90eddab127cf8b046418009f2125630ecb/tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662", size = 244713, upload-time = "2026-03-25T20:21:44.474Z" },+ { url = "https://files.pythonhosted.org/packages/df/6d/c5fad00d82b3c7a3ab6189bd4b10e60466f22cfe8a08a9394185c8a8111c/tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853", size = 252084, upload-time = "2026-03-25T20:21:45.62Z" },+ { url = "https://files.pythonhosted.org/packages/00/71/3a69e86f3eafe8c7a59d008d245888051005bd657760e96d5fbfb0b740c2/tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15", size = 247973, upload-time = "2026-03-25T20:21:46.937Z" },+ { url = "https://files.pythonhosted.org/packages/67/50/361e986652847fec4bd5e4a0208752fbe64689c603c7ae5ea7cb16b1c0ca/tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba", size = 256223, upload-time = "2026-03-25T20:21:48.467Z" },+ { url = "https://files.pythonhosted.org/packages/8c/9a/b4173689a9203472e5467217e0154b00e260621caa227b6fa01feab16998/tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6", size = 98973, upload-time = "2026-03-25T20:21:49.526Z" },+ { url = "https://files.pythonhosted.org/packages/14/58/640ac93bf230cd27d002462c9af0d837779f8773bc03dee06b5835208214/tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7", size = 109082, upload-time = "2026-03-25T20:21:50.506Z" },+ { url = "https://files.pythonhosted.org/packages/d5/2f/702d5e05b227401c1068f0d386d79a589bb12bf64c3d2c72ce0631e3bc49/tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232", size = 96490, upload-time = "2026-03-25T20:21:51.474Z" },+ { url = "https://files.pythonhosted.org/packages/45/4b/b877b05c8ba62927d9865dd980e34a755de541eb65fffba52b4cc495d4d2/tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4", size = 164263, upload-time = "2026-03-25T20:21:52.543Z" },+ { url = "https://files.pythonhosted.org/packages/24/79/6ab420d37a270b89f7195dec5448f79400d9e9c1826df982f3f8e97b24fd/tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c", size = 160736, upload-time = "2026-03-25T20:21:53.674Z" },+ { url = "https://files.pythonhosted.org/packages/02/e0/3630057d8eb170310785723ed5adcdfb7d50cb7e6455f85ba8a3deed642b/tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d", size = 270717, upload-time = "2026-03-25T20:21:55.129Z" },+ { url = "https://files.pythonhosted.org/packages/7a/b4/1613716072e544d1a7891f548d8f9ec6ce2faf42ca65acae01d76ea06bb0/tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41", size = 278461, upload-time = "2026-03-25T20:21:56.228Z" },+ { url = "https://files.pythonhosted.org/packages/05/38/30f541baf6a3f6df77b3df16b01ba319221389e2da59427e221ef417ac0c/tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c", size = 274855, upload-time = "2026-03-25T20:21:57.653Z" },+ { url = "https://files.pythonhosted.org/packages/77/a3/ec9dd4fd2c38e98de34223b995a3b34813e6bdadf86c75314c928350ed14/tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f", size = 283144, upload-time = "2026-03-25T20:21:59.089Z" },+ { url = "https://files.pythonhosted.org/packages/ef/be/605a6261cac79fba2ec0c9827e986e00323a1945700969b8ee0b30d85453/tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8", size = 108683, upload-time = "2026-03-25T20:22:00.214Z" },+ { url = "https://files.pythonhosted.org/packages/12/64/da524626d3b9cc40c168a13da8335fe1c51be12c0a63685cc6db7308daae/tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26", size = 121196, upload-time = "2026-03-25T20:22:01.169Z" },+ { url = "https://files.pythonhosted.org/packages/5a/cd/e80b62269fc78fc36c9af5a6b89c835baa8af28ff5ad28c7028d60860320/tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396", size = 100393, upload-time = "2026-03-25T20:22:02.137Z" },+ { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" },+]++[[package]]+name = "ty"+version = "0.0.15"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/4e/25/257602d316b9333089b688a7a11b33ebc660b74e8dacf400dc3dfdea1594/ty-0.0.15.tar.gz", hash = "sha256:4f9a5b8df208c62dba56e91b93bed8b5bb714839691b8cff16d12c983bfa1174", size = 5101936, upload-time = "2026-02-05T01:06:34.922Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ce/c5/35626e732b79bf0e6213de9f79aff59b5f247c0a1e3ce0d93e675ab9b728/ty-0.0.15-py3-none-linux_armv6l.whl", hash = "sha256:68e092458516c61512dac541cde0a5e4e5842df00b4e81881ead8f745ddec794", size = 10138374, upload-time = "2026-02-05T01:07:03.804Z" },+ { url = "https://files.pythonhosted.org/packages/d5/8a/48fd81664604848f79d03879b3ca3633762d457a069b07e09fb1b87edd6e/ty-0.0.15-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:79f2e75289eae3cece94c51118b730211af4ba5762906f52a878041b67e54959", size = 9947858, upload-time = "2026-02-05T01:06:47.453Z" },+ { url = "https://files.pythonhosted.org/packages/b6/85/c1ac8e97bcd930946f4c94db85b675561d590b4e72703bf3733419fc3973/ty-0.0.15-py3-none-macosx_11_0_arm64.whl", hash = "sha256:112a7b26e63e48cc72c8c5b03227d1db280cfa57a45f2df0e264c3a016aa8c3c", size = 9443220, upload-time = "2026-02-05T01:06:44.98Z" },+ { url = "https://files.pythonhosted.org/packages/3c/d9/244bc02599d950f7a4298fbc0c1b25cc808646b9577bdf7a83470b2d1cec/ty-0.0.15-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71f62a2644972975a657d9dc867bf901235cde51e8d24c20311067e7afd44a56", size = 9949976, upload-time = "2026-02-05T01:07:01.515Z" },+ { url = "https://files.pythonhosted.org/packages/7e/ab/3a0daad66798c91a33867a3ececf17d314ac65d4ae2bbbd28cbfde94da63/ty-0.0.15-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:9e48b42be2d257317c85b78559233273b655dd636fc61e7e1d69abd90fd3cba4", size = 9965918, upload-time = "2026-02-05T01:06:54.283Z" },+ { url = "https://files.pythonhosted.org/packages/39/4e/e62b01338f653059a7c0cd09d1a326e9a9eedc351a0f0de9db0601658c3d/ty-0.0.15-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:27dd5b52a421e6871c5bfe9841160331b60866ed2040250cb161886478ab3e4f", size = 10424943, upload-time = "2026-02-05T01:07:08.777Z" },+ { url = "https://files.pythonhosted.org/packages/65/b5/7aa06655ce69c0d4f3e845d2d85e79c12994b6d84c71699cfb437e0bc8cf/ty-0.0.15-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:76b85c9ec2219e11c358a7db8e21b7e5c6674a1fb9b6f633836949de98d12286", size = 10964692, upload-time = "2026-02-05T01:06:37.103Z" },+ { url = "https://files.pythonhosted.org/packages/13/04/36fdfe1f3c908b471e246e37ce3d011175584c26d3853e6c5d9a0364564c/ty-0.0.15-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a9e8204c61d8ede4f21f2975dce74efdb80fafb2fae1915c666cceb33ea3c90b", size = 10692225, upload-time = "2026-02-05T01:06:49.714Z" },+ { url = "https://files.pythonhosted.org/packages/13/41/5bf882649bd8b64ded5fbce7fb8d77fb3b868de1a3b1a6c4796402b47308/ty-0.0.15-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af87c3be7c944bb4d6609d6c63e4594944b0028c7bd490a525a82b88fe010d6d", size = 10516776, upload-time = "2026-02-05T01:06:52.047Z" },+ { url = "https://files.pythonhosted.org/packages/56/75/66852d7e004f859839c17ffe1d16513c1e7cc04bcc810edb80ca022a9124/ty-0.0.15-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:50dccf7398505e5966847d366c9e4c650b8c225411c2a68c32040a63b9521eea", size = 9928828, upload-time = "2026-02-05T01:06:56.647Z" },+ { url = "https://files.pythonhosted.org/packages/65/72/96bc16c7b337a3ef358fd227b3c8ef0c77405f3bfbbfb59ee5915f0d9d71/ty-0.0.15-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:bd797b8f231a4f4715110259ad1ad5340a87b802307f3e06d92bfb37b858a8f3", size = 9978960, upload-time = "2026-02-05T01:06:29.567Z" },+ { url = "https://files.pythonhosted.org/packages/a0/18/d2e316a35b626de2227f832cd36d21205e4f5d96fd036a8af84c72ecec1b/ty-0.0.15-py3-none-musllinux_1_2_i686.whl", hash = "sha256:9deb7f20e18b25440a9aa4884f934ba5628ef456dbde91819d5af1a73da48af3", size = 10135903, upload-time = "2026-02-05T01:06:59.256Z" },+ { url = "https://files.pythonhosted.org/packages/02/d3/b617a79c9dad10c888d7c15cd78859e0160b8772273637b9c4241a049491/ty-0.0.15-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7b31b3de031255b90a5f4d9cb3d050feae246067c87130e5a6861a8061c71754", size = 10615879, upload-time = "2026-02-05T01:07:06.661Z" },+ { url = "https://files.pythonhosted.org/packages/fb/b0/2652a73c71c77296a6343217063f05745da60c67b7e8a8e25f2064167fce/ty-0.0.15-py3-none-win32.whl", hash = "sha256:9362c528ceb62c89d65c216336d28d500bc9f4c10418413f63ebc16886e16cc1", size = 9578058, upload-time = "2026-02-05T01:06:42.928Z" },+ { url = "https://files.pythonhosted.org/packages/84/6e/08a4aedebd2a6ce2784b5bc3760e43d1861f1a184734a78215c2d397c1df/ty-0.0.15-py3-none-win_amd64.whl", hash = "sha256:4db040695ae67c5524f59cb8179a8fa277112e69042d7dfdac862caa7e3b0d9c", size = 10457112, upload-time = "2026-02-05T01:06:39.885Z" },+ { url = "https://files.pythonhosted.org/packages/b3/be/1991f2bc12847ae2d4f1e3ac5dcff8bb7bc1261390645c0755bb55616355/ty-0.0.15-py3-none-win_arm64.whl", hash = "sha256:e5a98d4119e77d6136461e16ae505f8f8069002874ab073de03fbcb1a5e8bf25", size = 9937490, upload-time = "2026-02-05T01:06:32.388Z" },+]++[[package]]+name = "typing-extensions"+version = "4.16.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },+]diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.jsonindex 8eec4f397..8e0f11da6 100644--- a/packages/js-sdk/package.json+++ b/packages/js-sdk/package.json@@ -24,6 +24,7 @@"types": "dist/index.d.ts","scripts": {"prepublishOnly": "pnpm build",+ "prebuild": "pnpm --dir ../dockerfile-utils-js build","build": "tsc --noEmit && tsdown","dev": "tsdown --watch","test": "vitest run",@@ -89,9 +90,9 @@"@bufbuild/protobuf": "^2.15.0","@connectrpc/connect": "^2.2.0","@connectrpc/connect-web": "^2.2.0",+ "@e2b/dockerfile-utils": "workspace:^","chalk": "^5.6.2","compare-versions": "^6.1.1",- "dockerfile-ast": "^0.7.1","glob": "^13.0.6","openapi-fetch": "^0.17.0","platform": "^1.3.6",diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex 1799643be..be24301a3 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -167,6 +167,7 @@ export { E2B, type E2BClientOpts } from './client'export default Sandboxexport * from './template'+export { DockerfileSyntaxError } from './template/dockerfileParser'export {ReadyCmd,diff --git a/packages/js-sdk/src/template/dockerfileParser.ts b/packages/js-sdk/src/template/dockerfileParser.tsindex 6ed62b57a..e89e20954 100644--- a/packages/js-sdk/src/template/dockerfileParser.ts+++ b/packages/js-sdk/src/template/dockerfileParser.ts@@ -1,12 +1,18 @@-import { CopyItem } from './types'-import {- Argument,- DockerfileParser,- Instruction as DockerfileInstruction,- ModifiableInstruction,-} from 'dockerfile-ast'import fs from 'node:fs'+import { shellQuote } from '../utils'+import { CopyItem } from './types'import { ReadyCmd, waitForTimeout } from './readycmd'+import {+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileSyntaxError,+ ShellLex,+ chompHeredocContent,+ parseDockerfileAst,+ parseHeredoc,+} from '@e2b/dockerfile-utils'++export { DockerfileSyntaxError }export interface DockerfileParseResult {baseImage: string@@ -37,280 +43,683 @@ export interface DockerfileParserInterface {): DockerfileFinalParserInterface}+type FlagType = 'bool' | 'string'++interface FlagSpec {+ type: FlagType+ /** The flag is accepted but has no effect; a warning is emitted. */+ ignored?: boolean+}++const RUN_FLAGS: Record<string, FlagSpec> = {+ mount: { type: 'string', ignored: true },+ network: { type: 'string', ignored: true },+ security: { type: 'string', ignored: true },+ device: { type: 'string', ignored: true },+}++const COPY_FLAGS: Record<string, FlagSpec> = {+ chown: { type: 'string' },+ chmod: { type: 'string' },+ from: { type: 'string' },+ link: { type: 'bool', ignored: true },+ exclude: { type: 'string', ignored: true },+ parents: { type: 'bool', ignored: true },+}++const ADD_FLAGS: Record<string, FlagSpec> = {+ ...COPY_FLAGS,+ 'keep-git-dir': { type: 'bool', ignored: true },+ checksum: { type: 'string', ignored: true },+ unpack: { type: 'bool', ignored: true },+}++const FROM_FLAGS: Record<string, FlagSpec> = {+ platform: { type: 'string', ignored: true },+}++// Metadata-only instructions that have no equivalent in a template.+const IGNORED_INSTRUCTIONS = new Set([+ 'EXPOSE',+ 'VOLUME',+ 'LABEL',+ 'MAINTAINER',+])++/** A heredoc delimiter that does not occur in the content it wraps. */+function heredocTerminator(name: string, content: string): string {+ let terminator = `E2B_HEREDOC_${name.replace(/[^A-Za-z0-9_]/g, '_')}`+ while (content.includes(terminator)) {+ terminator += '_'+ }+ return terminator+}++function withTrailingNewline(content: string): string {+ return content === '' || content.endsWith('\n') ? content : content + '\n'+}++const VARIABLE_NAME = /\p{Nd}+|[@*#?\-$!0]|[\p{L}\p{Nd}_]+/uy++function shellLiteral(ch: string, stopChar?: string): string {+ return ch === '\\' || ch === '`' || ch === '$' || ch === stopChar+ ? '\\' + ch+ : ch+}+/**- * Parse a Dockerfile and convert it to Template SDK format- *- * @param dockerfileContentOrPath Either the Dockerfile content as a string,- * or a path to a Dockerfile file- * @param templateBuilder Interface providing template builder methods- * @returns Parsed Dockerfile result with base image and instructions+ * Rewrite an expandable heredoc body so that the shell applies Docker's+ * rules: `$VAR` / `${VAR...}` are substituted, a backslash escapes the next+ * character, and everything else - `$(...)` and backticks included - is+ * literal. Backslashes inside `#`, `%` and `/` patterns stay significant to+ * the shell's pattern matching, as they do for Docker.*/-export function parseDockerfile(- dockerfileContentOrPath: string,- templateBuilder: DockerfileParserInterface-): DockerfileParseResult {- // Check if input is a file path that exists- let dockerfileContent: string- try {- if (- fs.existsSync(dockerfileContentOrPath) &&- fs.statSync(dockerfileContentOrPath).isFile()- ) {- // Read the file content- dockerfileContent = fs.readFileSync(dockerfileContentOrPath, 'utf-8')- } else {- // Treat as content directly- dockerfileContent = dockerfileContentOrPath- }- } catch {- // If there's any error checking the file, treat as content- dockerfileContent = dockerfileContentOrPath- }+function expandableHeredocBody(content: string, line: number): string {+ let i = 0- const dockerfile = DockerfileParser.parse(dockerfileContent)- const instructions = dockerfile.getInstructions()+ function missing(stopChar: string): never {+ const what = stopChar === '/' ? "'/' in ${}" : "'}'"+ throw new DockerfileSyntaxError(`syntax error: missing ${what}`, line)+ }- // Check for multi-stage builds- const fromInstructions = instructions.filter(- (instruction) => instruction.getKeyword() === 'FROM'- )+ function name(): string {+ VARIABLE_NAME.lastIndex = i+ const match = VARIABLE_NAME.exec(content)+ if (!match) {+ return ''+ }+ i += match[0].length+ return match[0]+ }- if (fromInstructions.length > 1) {- throw new Error('Multi-stage Dockerfiles are not supported')+ function variable(): string {+ if (content[i] !== '{') {+ const varName = name()+ return varName === '' ? '\\$' : '$' + varName+ }+ i+++ if (i >= content.length) {+ missing('}')+ }+ if (content[i] === '{' || content[i] === '}' || content[i] === ':') {+ throw new DockerfileSyntaxError('syntax error: bad substitution', line)+ }+ const varName = name()+ if (i >= content.length) {+ missing('}')+ }+ let modifier = content[i++]+ if (modifier === '}') {+ return `\${${varName}}`+ }+ if (modifier === '/') {+ if (content[i] === '/') {+ modifier += content[i++]+ }+ const pattern = scan('/', true)+ return `\${${varName}${modifier}${pattern}/${scan('}', true)}}`+ }+ if (modifier === ':') {+ if (i >= content.length) {+ missing('}')+ }+ modifier += content[i++]+ }+ const op = modifier[modifier.length - 1]+ const isPattern = op === '#' || op === '%'+ if (!'+-?#%'.includes(op) || (modifier.length === 2 && isPattern)) {+ throw new DockerfileSyntaxError(+ `unsupported modifier (${modifier}) in substitution`,+ line+ )+ }+ return `\${${varName}${modifier}${scan('}', isPattern)}}`}- if (fromInstructions.length === 0) {- throw new Error('Dockerfile must contain a FROM instruction')+ function scan(stopChar?: string, rawEscapes = false): string {+ let out = ''+ while (i < content.length) {+ const ch = content[i++]+ if (ch === stopChar) {+ return out+ }+ if (ch === '\\') {+ if (i < content.length) {+ const next = content[i++]+ out += rawEscapes ? '\\' + next : shellLiteral(next, stopChar)+ }+ } else if (ch === '$') {+ out += variable()+ } else {+ out += ch === '`' ? '\\`' : ch+ }+ }+ if (stopChar !== undefined) {+ missing(stopChar)+ }+ return out}- // Set the base image from the first FROM instruction- const fromInstruction = fromInstructions[0]- const argumentsData = fromInstruction.getArguments()- let baseImage = 'e2bdev/base' // default fallback- let userChanged = false- let workdirChanged = false- if (argumentsData && argumentsData.length > 0) {- baseImage = argumentsData[0].getValue()+ return scan()+}++function shellJoin(words: string[]): string {+ return words.map(shellQuote).join(' ')+}++interface StartCommand {+ json: boolean+ args: string[]+}++class DockerfileConverter {+ private readonly lex: ShellLex+ /** Expands the `ARG` / `ENV` values declared earlier in the Dockerfile. */+ private readonly envLex: ShellLex+ private readonly vars = new Map<string, string>()+ private userChanged = false+ private workdirChanged = false+ private cmd?: StartCommand+ private entrypoint?: StartCommand++ constructor(+ private readonly templateBuilder: DockerfileParserInterface,+ escapeToken: string+ ) {+ this.lex = new ShellLex(escapeToken)+ this.envLex = new ShellLex(escapeToken, {+ env: this.vars,+ skipUnsetEnv: false,+ })}- // Set the user and workdir to the Docker defaults- templateBuilder.setUser('root')- templateBuilder.setWorkdir('/')+ convert(instructions: DockerfileInstruction[]): DockerfileParseResult {+ const fromInstructions = instructions.filter((i) => i.name === 'FROM')+ if (fromInstructions.length > 1) {+ throw new DockerfileSyntaxError(+ 'Multi-stage Dockerfiles are not supported'+ )+ }+ if (fromInstructions.length === 0) {+ throw new DockerfileSyntaxError(+ 'Dockerfile must contain a FROM instruction'+ )+ }- // Process all other instructions- for (const instruction of instructions) {- const keyword = instruction.getKeyword()+ const fromInstruction = fromInstructions[0]+ const baseImage = this.handleFrom(fromInstruction)- switch (keyword) {- case 'FROM':- // Already handled above- break+ // Set the user and workdir to the Docker defaults+ this.templateBuilder.setUser('root')+ this.templateBuilder.setWorkdir('/')+ for (const instruction of instructions) {+ if (instruction.name === 'FROM') {+ continue+ }+ if (+ instruction.startLine < fromInstruction.startLine &&+ instruction.name !== 'ARG'+ ) {+ throw new DockerfileSyntaxError(+ `${instruction.name} must be preceded by a FROM instruction`,+ instruction.startLine+ )+ }+ this.handleInstruction(instruction)+ }++ this.applyStartCmd()++ // Set the user and workdir to the E2B defaults+ if (!this.userChanged) {+ this.templateBuilder.setUser('user')+ }+ if (!this.workdirChanged) {+ this.templateBuilder.setWorkdir('/home/user')+ }++ return { baseImage }+ }++ private handleInstruction(instruction: DockerfileInstruction) {+ switch (instruction.name) {case 'RUN':- handleRunInstruction(instruction, templateBuilder)+ this.handleRun(instruction)break-case 'COPY':+ this.handleCopy(instruction, COPY_FLAGS)+ breakcase 'ADD':- handleCopyInstruction(- instruction as ModifiableInstruction,- templateBuilder- )+ this.handleCopy(instruction, ADD_FLAGS)break-case 'WORKDIR':- handleWorkdirInstruction(instruction, templateBuilder)- workdirChanged = true+ this.templateBuilder.setWorkdir(this.expandSingle(instruction))+ this.workdirChanged = truebreak-case 'USER':- handleUserInstruction(instruction, templateBuilder)- userChanged = true+ this.templateBuilder.setUser(this.expandSingle(instruction))+ this.userChanged = truebreak-case 'ENV':- case 'ARG':- handleEnvInstruction(instruction, templateBuilder)- break-- case 'EXPOSE':- // EXPOSE is not directly supported in our SDK, so we'll skip it+ this.handleEnv(instruction)break-- case 'VOLUME':- // VOLUME is not directly supported in our SDK, so we'll skip it+ case 'ARG':+ this.handleArg(instruction)break-case 'CMD':+ this.parseFlags(instruction, {})+ this.cmd = { json: instruction.json, args: instruction.args }+ breakcase 'ENTRYPOINT':- handleCmdEntrypointInstruction(instruction, templateBuilder)+ this.parseFlags(instruction, {})+ this.entrypoint = { json: instruction.json, args: instruction.args }break-default:- console.warn(`Unsupported instruction: ${keyword}`)+ if (!IGNORED_INSTRUCTIONS.has(instruction.name)) {+ console.warn(`Unsupported instruction: ${instruction.name}`)+ }break}}- // Set the user and workdir to the E2B defaults- if (!userChanged) {- templateBuilder.setUser('user')+ /** Resolve quotes and escapes in a word, keeping `$VAR` references. */+ private expand(+ instruction: DockerfileInstruction,+ word: string,+ lex = this.lex+ ): string {+ try {+ return lex.processWord(word)+ } catch (err) {+ throw new DockerfileSyntaxError(+ err instanceof Error ? err.message : String(err),+ instruction.startLine+ )+ }}- if (!workdirChanged) {- templateBuilder.setWorkdir('/home/user')++ private expandSingle(instruction: DockerfileInstruction): string {+ this.parseFlags(instruction, {})+ if (instruction.args.length !== 1) {+ throw new DockerfileSyntaxError(+ `${instruction.name} requires exactly one argument`,+ instruction.startLine+ )+ }+ return this.expand(instruction, instruction.args[0])}- return {- baseImage,+ private parseFlags(+ instruction: DockerfileInstruction,+ specs: Record<string, FlagSpec>+ ): Record<string, string> {+ const values: Record<string, string> = {}+ for (const flag of instruction.flags) {+ if (!flag.startsWith('--')) {+ throw new DockerfileSyntaxError(+ `arg should start with -- : ${flag}`,+ instruction.startLine+ )+ }+ const body = flag.slice(2)+ const eq = body.indexOf('=')+ const name = eq === -1 ? body : body.slice(0, eq)+ const rawValue = eq === -1 ? undefined : body.slice(eq + 1)++ const spec = Object.hasOwn(specs, name) ? specs[name] : undefined+ if (!spec) {+ throw new DockerfileSyntaxError(+ `unknown flag: ${name}`,+ instruction.startLine+ )+ }+ if (name in values) {+ throw new DockerfileSyntaxError(+ `duplicate flag specified: ${name}`,+ instruction.startLine+ )+ }++ let value: string+ if (spec.type === 'bool') {+ if (rawValue === undefined || rawValue === '' || rawValue === 'true') {+ value = 'true'+ } else if (rawValue === 'false') {+ value = 'false'+ } else {+ throw new DockerfileSyntaxError(+ `expecting boolean value for flag ${name}, not: ${rawValue}`,+ instruction.startLine+ )+ }+ } else {+ if (rawValue === undefined) {+ throw new DockerfileSyntaxError(+ `missing a value on flag: ${name}`,+ instruction.startLine+ )+ }+ value = rawValue+ }++ if (spec.ignored) {+ console.warn(+ `Ignoring unsupported ${instruction.name} flag --${name} (line ${instruction.startLine})`+ )+ continue+ }+ values[name] = value+ }+ return values}-}-function handleRunInstruction(- instruction: DockerfileInstruction,- templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- if (argumentsData && argumentsData.length > 0) {- const command = argumentsData- .map((arg: Argument) => arg.getValue())- .join(' ')- templateBuilder.runCmd(command)+ private handleFrom(instruction: DockerfileInstruction): string {+ this.parseFlags(instruction, FROM_FLAGS)+ const args = instruction.args+ if (args.length === 3 && args[1].toLowerCase() === 'as') {+ // stage alias is irrelevant for a single-stage build+ } else if (args.length !== 1) {+ throw new DockerfileSyntaxError(+ 'FROM requires either one or three arguments',+ instruction.startLine+ )+ }+ return this.expand(instruction, args[0])}-}-function handleCopyInstruction(- instruction: ModifiableInstruction,- templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- if (argumentsData && argumentsData.length >= 2) {- const dest = argumentsData[argumentsData.length - 1].getValue()- const sources = argumentsData- .slice(0, -1)- .map((arg: Argument) => arg.getValue())+ private handleRun(instruction: DockerfileInstruction) {+ this.parseFlags(instruction, RUN_FLAGS)+ const { args, json, heredocs } = instruction+ if (args.length === 0) {+ throw new DockerfileSyntaxError(+ 'RUN requires at least one argument',+ instruction.startLine+ )+ }++ let command: string+ if (json) {+ command = shellJoin(args)+ } else if (heredocs.length > 0) {+ command = this.runWithHeredocs(args[0], heredocs)+ } else {+ command = args[0]+ }+ this.templateBuilder.runCmd(command)+ }++ private runWithHeredocs(line: string, heredocs: DockerfileHeredoc[]): string {+ const heredocContent = (heredoc: DockerfileHeredoc) =>+ heredoc.chomp ? chompHeredocContent(heredoc.content) : heredoc.content- let user: string | undefined- const flags = instruction.getFlags()- const chownFlag = flags.find((flag) => flag.getName() === 'chown')- if (chownFlag) {- user = chownFlag.getValue() ?? undefined+ // `RUN <<EOF` on its own: the heredoc body is the script itself.+ if (heredocs.length === 1 && parseHeredoc(line.trim())) {+ const heredoc = heredocs[0]+ const content = heredocContent(heredoc)+ if (!content.startsWith('#!')) {+ return content+ }+ // A shebang script: write it to a temporary file and execute it.+ const script = shellQuote(`/tmp/${heredoc.name}`)+ const terminator = heredocTerminator(heredoc.name, content)+ return (+ `cat <<'${terminator}' >${script}\n` ++ withTrailingNewline(content) ++ `${terminator}\n` ++ `chmod +x ${script} && ${script}\n` ++ `E2B_EXIT=$?; rm -f ${script}; exit $E2B_EXIT`+ )}- for (const src of sources) {- templateBuilder.copy(src, dest, { user })+ // Heredocs used as part of a larger command (`cat <<EOF > file`,+ // `python3 <<EOF`): rebuild the heredoc so the shell handles it.+ let full = line+ for (const heredoc of heredocs) {+ full += '\n' + heredoc.content + heredoc.name}+ return full}-}-function handleWorkdirInstruction(- instruction: DockerfileInstruction,- templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- if (argumentsData && argumentsData.length > 0) {- const workdir = argumentsData[0].getValue()- templateBuilder.setWorkdir(workdir)+ private handleCopy(+ instruction: DockerfileInstruction,+ specs: Record<string, FlagSpec>+ ) {+ const flags = this.parseFlags(instruction, specs)+ if (instruction.args.length < 2) {+ throw new DockerfileSyntaxError(+ `${instruction.name} requires at least two arguments`,+ instruction.startLine+ )+ }+ if (flags.from !== undefined) {+ throw new DockerfileSyntaxError(+ `${instruction.name} --from is not supported (multi-stage builds are not supported)`,+ instruction.startLine+ )+ }++ const user =+ flags.chown !== undefined+ ? this.expand(instruction, flags.chown)+ : undefined+ let mode: number | undefined+ if (flags.chmod !== undefined) {+ const chmod = this.expand(instruction, flags.chmod)+ const resolved = this.expand(instruction, flags.chmod, this.envLex)+ if (!/^[0-7]{3,4}$/.test(resolved)) {+ const detail = resolved === chmod ? '' : ` (resolves to "${resolved}")`+ throw new DockerfileSyntaxError(+ `invalid chmod value "${chmod}"${detail}, expected an octal mode such as 0755`,+ instruction.startLine+ )+ }+ mode = parseInt(resolved, 8)+ }++ // Heredoc markers are recognized on the raw tokens, like the AST does:+ // a quoted `"<<EOF"` is a literal file name, not a heredoc.+ const rawDest = instruction.args[instruction.args.length - 1]+ if (parseHeredoc(rawDest)) {+ throw new DockerfileSyntaxError(+ `${instruction.name} cannot accept a heredoc as a destination`,+ instruction.startLine+ )+ }+ const dest = this.expand(instruction, rawDest)++ const heredocsByName = new Map(+ instruction.heredocs.map((heredoc) => [heredoc.name, heredoc])+ )++ for (const rawSrc of instruction.args.slice(0, -1)) {+ const heredoc = parseHeredoc(rawSrc)+ if (heredoc) {+ const content = heredocsByName.get(heredoc.name)+ if (!content) {+ throw new DockerfileSyntaxError(+ `missing heredoc content for ${heredoc.name}`,+ instruction.startLine+ )+ }+ this.copyHeredoc(content, dest, user, mode, instruction.startLine)+ continue+ }+ const src = this.expand(instruction, rawSrc)+ if (instruction.name === 'ADD' && /^[a-z][a-z0-9+.-]*:\/\//i.test(src)) {+ throw new DockerfileSyntaxError(+ `ADD from a remote URL is not supported: ${src}`,+ instruction.startLine+ )+ }+ this.templateBuilder.copy(src, dest, { user, mode })+ }}-}-function handleUserInstruction(- instruction: DockerfileInstruction,- templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- if (argumentsData && argumentsData.length > 0) {- const user = argumentsData[0].getValue()- templateBuilder.setUser(user)+ /** `COPY <<EOF /path` writes the heredoc body to a file inside the sandbox. */+ private copyHeredoc(+ heredoc: DockerfileHeredoc,+ dest: string,+ user: string | undefined,+ mode: number | undefined,+ line: number+ ) {+ let content = heredoc.chomp+ ? chompHeredocContent(heredoc.content)+ : heredoc.content+ if (heredoc.expand) {+ content = expandableHeredocBody(content, line)+ }+ const plainTerminator = heredocTerminator(heredoc.name, content)+ const terminator = heredoc.expand ? plainTerminator : `'${plainTerminator}'`+ const target = '"$E2B_HEREDOC_DEST"'++ // Like Docker, a dest that is a directory receives a file named after the heredoc.+ let command = dest.endsWith('/')+ ? `E2B_HEREDOC_DEST=${shellQuote(dest + heredoc.name)}\n`+ : `E2B_HEREDOC_DEST=${shellQuote(dest)}\n` ++ `if [ -d ${target} ]; then E2B_HEREDOC_DEST=${target}/${shellQuote(heredoc.name)}; fi\n`+ command +=+ `mkdir -p "$(dirname ${target})" && cat <<${terminator} >${target}\n` ++ withTrailingNewline(content) ++ plainTerminator+ if (user !== undefined) {+ command += `\nchown ${shellQuote(user)} ${target}`+ }+ if (mode !== undefined) {+ command += `\nchmod ${mode.toString(8)} ${target}`+ }+ // COPY writes as the builder (root), independent of the current USER.+ this.templateBuilder.runCmd(command, { user: 'root' })}-}-function handleEnvInstruction(- instruction: DockerfileInstruction,- templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- const keyword = instruction.getKeyword()-- if (argumentsData && argumentsData.length >= 1) {- const envVars: Record<string, string> = {}-- if (argumentsData.length === 2) {- // ENV key value format OR multiple key=value pairs (from line continuation)- const firstArg = argumentsData[0].getValue()- const secondArg = argumentsData[1].getValue()-- // Check if both arguments contain '=' (multiple key=value pairs)- if (firstArg.includes('=') && secondArg.includes('=')) {- // Both are key=value pairs (line continuation)- for (const arg of argumentsData) {- const envString = arg.getValue()- const equalIndex = envString.indexOf('=')- if (equalIndex > 0) {- const key = envString.substring(0, equalIndex)- const value = envString.substring(equalIndex + 1)- envVars[key] = value+ private handleEnv(instruction: DockerfileInstruction) {+ this.parseFlags(instruction, {})+ const { args } = instruction+ if (args.length === 0) {+ throw new DockerfileSyntaxError(+ 'ENV requires at least one argument',+ instruction.startLine+ )+ }+ const envs: Record<string, string> = {}+ for (let i = 0; i + 2 < args.length; i += 3) {+ const key = this.expand(instruction, args[i])+ if (key === '') {+ throw new DockerfileSyntaxError(+ 'ENV names can not be blank',+ instruction.startLine+ )+ }+ envs[key] = this.expand(instruction, args[i + 1])+ this.vars.set(key, this.expand(instruction, args[i + 1], this.envLex))+ }+ this.templateBuilder.setEnvs(envs)+ }++ private handleArg(instruction: DockerfileInstruction) {+ this.parseFlags(instruction, {})+ const { args } = instruction+ if (args.length === 0) {+ throw new DockerfileSyntaxError(+ 'ARG requires at least one argument',+ instruction.startLine+ )+ }+ const envs: Record<string, string> = {}+ for (const arg of args) {+ const eq = arg.indexOf('=')+ const key = this.expand(instruction, eq === -1 ? arg : arg.slice(0, eq))+ if (key === '') {+ throw new DockerfileSyntaxError(+ 'ARG names can not be blank',+ instruction.startLine+ )+ }+ const value = arg.slice(eq + 1)+ envs[key] = eq === -1 ? '' : this.expand(instruction, value)+ this.vars.set(+ key,+ eq === -1 ? '' : this.expand(instruction, value, this.envLex)+ )+ }+ this.templateBuilder.setEnvs(envs)+ }++ /**+ * Combine ENTRYPOINT and CMD following Docker's rules:+ * - exec-form ENTRYPOINT gets CMD appended as arguments+ * (a shell-form CMD is appended as `/bin/sh -c <cmd>`),+ * - shell-form ENTRYPOINT ignores CMD,+ * - without ENTRYPOINT the CMD is used as-is.+ */+ private applyStartCmd() {+ const { cmd, entrypoint } = this+ let command: string | undefined++ if (entrypoint) {+ if (entrypoint.json) {+ const words = [...entrypoint.args]+ if (cmd) {+ if (cmd.json) {+ words.push(...cmd.args)+ } else if (cmd.args.length > 0) {+ words.push('/bin/sh', '-c', cmd.args[0])}}+ command = words.length > 0 ? shellJoin(words) : undefined} else {- // Traditional ENV key value format- envVars[firstArg] = secondArg- }- } else if (argumentsData.length === 1) {- // ENV/ARG key=value format (single argument) or ARG key (without default)- const envString = argumentsData[0].getValue()-- // Check if it's a simple key=value or just a key (for ARG without default)- const equalIndex = envString.indexOf('=')- if (equalIndex > 0) {- const key = envString.substring(0, equalIndex)- const value = envString.substring(equalIndex + 1)- envVars[key] = value- } else if (keyword === 'ARG' && envString.trim()) {- // ARG without default value - set as empty ENV- const key = envString.trim()- envVars[key] = ''+ command = entrypoint.args.length > 0 ? entrypoint.args[0] : undefined}- } else {- // Multiple arguments (from line continuation with backslashes)- for (const arg of argumentsData) {- const envString = arg.getValue()- const equalIndex = envString.indexOf('=')- if (equalIndex > 0) {- const key = envString.substring(0, equalIndex)- const value = envString.substring(equalIndex + 1)- envVars[key] = value- } else if (keyword === 'ARG') {- // ARG without default value- const key = envString- envVars[key] = ''- }+ } else if (cmd) {+ if (cmd.json) {+ command = cmd.args.length > 0 ? shellJoin(cmd.args) : undefined+ } else {+ command = cmd.args.length > 0 ? cmd.args[0] : undefined}}- // Call setEnvs once with all environment variables from this instruction- if (Object.keys(envVars).length > 0) {- templateBuilder.setEnvs(envVars)+ if (command !== undefined && command.trim() !== '') {+ this.templateBuilder.setStartCmd(command, waitForTimeout(20_000))}}}-function handleCmdEntrypointInstruction(- instruction: DockerfileInstruction,+function readDockerfile(dockerfileContentOrPath: string): string {+ try {+ if (+ fs.existsSync(dockerfileContentOrPath) &&+ fs.statSync(dockerfileContentOrPath).isFile()+ ) {+ return fs.readFileSync(dockerfileContentOrPath, 'utf-8')+ }+ } catch {+ // If there's any error checking the file, treat as content+ }+ return dockerfileContentOrPath+}++/**+ * Parse a Dockerfile and convert it to Template SDK format+ *+ * @param dockerfileContentOrPath Either the Dockerfile content as a string,+ * or a path to a Dockerfile file+ * @param templateBuilder Interface providing template builder methods+ * @returns Parsed Dockerfile result with base image and instructions+ */+export function parseDockerfile(+ dockerfileContentOrPath: string,templateBuilder: DockerfileParserInterface-): void {- const argumentsData = instruction.getArguments()- if (argumentsData && argumentsData.length > 0) {- let command = argumentsData.map((arg: Argument) => arg.getValue()).join(' ')+): DockerfileParseResult {+ const dockerfileContent = readDockerfile(dockerfileContentOrPath)- try {- const parsedCommand = JSON.parse(command)- if (Array.isArray(parsedCommand)) {- command = parsedCommand.join(' ')- }- } catch {- // Do nothing- }+ const ast = parseDockerfileAst(dockerfileContent)- templateBuilder.setStartCmd(command, waitForTimeout(20_000))+ for (const warning of ast.warnings) {+ console.warn(`${warning.message} (line ${warning.line})`)}++ return new DockerfileConverter(templateBuilder, ast.escapeToken).convert(+ ast.instructions+ )}diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.tsindex b54182fbc..7184ca60b 100644--- a/packages/js-sdk/src/template/index.ts+++ b/packages/js-sdk/src/template/index.ts@@ -613,7 +613,7 @@ export class TemplateBasesrcString,dest.toString(),options?.user ?? '',- options?.mode ? padOctal(options.mode) : '',+ options?.mode !== undefined ? padOctal(options.mode) : '',]this.instructions.push({@@ -694,7 +694,7 @@ export class TemplateBase): TemplateBuilder {const paths = Array.isArray(path) ? path : [path]const args = ['mkdir', '-p']- if (options?.mode) {+ if (options?.mode !== undefined) {args.push(`-m ${padOctal(options.mode)}`)}args.push(...paths.map((p) => shellQuote(p.toString())))diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.tsindex 8504af5fa..9ecc0cf25 100644--- a/packages/js-sdk/src/template/utils.ts+++ b/packages/js-sdk/src/template/utils.ts@@ -7,7 +7,7 @@ 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 { PatternMatcher } from './dockerignore'+import { PatternMatcher } from '@e2b/dockerfile-utils'import type { IgnoreLike, Path } from 'glob'import type { BuildOptions } from './types'@@ -118,8 +118,9 @@ export function readDockerignore(contextPath: string): string[] {.replace(/^\uFEFF/, '')return content.split('\n')+ .filter((line) => !line.startsWith('#')).map((line) => line.trim())- .filter((line) => line && !line.startsWith('#'))+ .filter((line) => line)}/**@@ -168,11 +169,17 @@ function createIgnoreMatcher(contextPath: string): IgnoreLike {const absoluteContextPath = path.resolve(contextPath)- const matcher = new PatternMatcher(- ignorePatterns.map((pattern) =>- normalizeIgnorePattern(pattern, absoluteContextPath)+ let matcher: PatternMatcher+ try {+ matcher = new PatternMatcher(+ ignorePatterns.map((pattern) =>+ normalizeIgnorePattern(pattern, absoluteContextPath)+ ),+ { backslashIsSeparator: path.sep === '\\' })- )+ } catch (err) {+ throw new TemplateError((err as Error).message)+ }const ignored = (p: Path) => {const relativePath = p.relativePosix()diff --git a/packages/js-sdk/tests/template/methods/fromDockerfile.test.ts b/packages/js-sdk/tests/template/methods/fromDockerfile.test.tsindex 3b2f7256d..e491f76ad 100644--- a/packages/js-sdk/tests/template/methods/fromDockerfile.test.ts+++ b/packages/js-sdk/tests/template/methods/fromDockerfile.test.ts@@ -1,5 +1,5 @@import { buildTemplateTest } from '../../setup'-import { Template } from '../../../src'+import { DockerfileSyntaxError, Template } from '../../../src'import { InstructionType } from '../../../src/template/types'import { assert } from 'vitest'@@ -196,3 +196,370 @@ COPY --chown=anotheruser config.json /config/`assert.equal(copyInstruction2.args[1], '/config/')assert.equal(copyInstruction2.args[2], 'anotheruser') // user from --chown (without group)})++function instructionsOf(template: unknown) {+ // @ts-expect-error - instructions is not a property of TemplateBuilder+ return template.instructions as { type: InstructionType; args: string[] }[]+}++buildTemplateTest('fromDockerfile with quoted ENV and ARG values', () => {+ const dockerfile = `FROM node:24+ENV A="hello world" B='single quoted' C=plain D=escaped\\ space+ENV LEGACY some value with spaces+ENV MULTI=1 \\+ # comment inside continuation+ LINE="two \\+words"+ARG VERSION=1.0 NAME="with space" EMPTY+ENV REF="$HOME/bin:\${PATH}"`++ const template = Template().fromDockerfile(dockerfile)+ const envs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.ENV)+ .map((i) => i.args)++ assert.deepEqual(envs, [+ [+ 'A',+ 'hello world',+ 'B',+ 'single quoted',+ 'C',+ 'plain',+ 'D',+ 'escaped space',+ ],+ ['LEGACY', 'some value with spaces'],+ ['MULTI', '1', 'LINE', 'two words'],+ ['VERSION', '1.0', 'NAME', 'with space', 'EMPTY', ''],+ ['REF', '$HOME/bin:${PATH}'],+ ])+})++buildTemplateTest(+ 'fromDockerfile with mixed-case keywords and AS alias',+ () => {+ const dockerfile = `from node:24 As Builder+run echo hi+Workdir /app+uSeR node`++ const template = Template().fromDockerfile(dockerfile)+ // @ts-expect-error - baseImage is not a property of TemplateBuilder+ assert.equal(template.baseImage, 'node:24')+ const instructions = instructionsOf(template)+ assert.equal(instructions[2].type, InstructionType.RUN)+ assert.deepEqual(instructions[2].args, ['echo hi'])+ assert.deepEqual(instructions[3].args, ['/app'])+ assert.deepEqual(instructions[4].args, ['node'])+ }+)++buildTemplateTest(+ 'fromDockerfile preserves whitespace in RUN and uses shell form',+ () => {+ const dockerfile = `FROM node:24+RUN echo "a b" && \\+ echo 'c d'+RUN ["echo", "hello world", "it's"]`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ `echo "a b" && echo 'c d'`,+ `echo 'hello world' 'it'"'"'s'`,+ ])+ }+)++buildTemplateTest('fromDockerfile with escape directive', () => {+ const dockerfile = `# escape=\`+FROM node:24+RUN echo one \`+ && echo two+ENV P="C:\\tools"`++ const template = Template().fromDockerfile(dockerfile)+ const instructions = instructionsOf(template)+ assert.deepEqual(instructions[2].args, ['echo one && echo two'])+ assert.deepEqual(instructions[3].args, ['P', 'C:\\tools'])+})++buildTemplateTest('fromDockerfile with COPY --chmod and quoted paths', () => {+ const dockerfile = `FROM node:24+COPY --chmod=755 --chown=app:app "my file.txt" other.txt /dest/+COPY ["json file.txt", "/dest/"]+ADD archive.tar.gz /opt/`++ const template = Template().fromDockerfile(dockerfile)+ const copies = instructionsOf(template)+ .filter((i) => i.type === InstructionType.COPY)+ .map((i) => i.args)++ assert.deepEqual(copies, [+ ['my file.txt', '/dest/', 'app:app', '0755'],+ ['other.txt', '/dest/', 'app:app', '0755'],+ ['json file.txt', '/dest/', '', ''],+ ['archive.tar.gz', '/opt/', '', ''],+ ])+})++buildTemplateTest('fromDockerfile with heredocs', () => {+ const dockerfile = `FROM node:24+RUN <<EOF+npm install+npm run build+EOF+RUN <<-EOT+\techo tabbed+EOT+RUN python3 - <<PY+print("hi")+PY+RUN 3<<FD+touch /tmp/fd+FD+COPY <<'CONF' /etc/app.conf+key=$VALUE+CONF`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ 'npm install\nnpm run build\n',+ 'echo tabbed\n',+ 'python3 - <<PY\nprint("hi")\nPY',+ 'touch /tmp/fd\n',+ `E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/CONF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<'E2B_HEREDOC_CONF' >"$E2B_HEREDOC_DEST"\nkey=$VALUE\nE2B_HEREDOC_CONF`,+ ])+})++buildTemplateTest('fromDockerfile COPY heredoc runs as root', () => {+ const dockerfile = `FROM node:24+USER app+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF+x=1+EOF`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args)++ assert.deepEqual(runs, [+ [+ `E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF_ >"$E2B_HEREDOC_DEST"\nE2B_HEREDOC_EOF\nx=1\nE2B_HEREDOC_EOF_`,+ 'root',+ ],+ ])+})++buildTemplateTest(+ 'fromDockerfile heredoc terminator avoids the content',+ () => {+ const dockerfile = `FROM node:24+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_+E2B_HEREDOC_EOF+EOF`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ `E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF____ >"$E2B_HEREDOC_DEST"\nE2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_\nE2B_HEREDOC_EOF\nE2B_HEREDOC_EOF____`,+ ])+ }+)++buildTemplateTest(+ 'fromDockerfile COPY heredoc into a directory expands only variables',+ () => {+ const dockerfile = `FROM node:24+COPY <<EOF /etc/+run \`npm start\` and $(id) for $USER, \\$(literal) and \${HOME:-$(x)}+EOF+COPY <<EOF .+x+EOF`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ 'E2B_HEREDOC_DEST=/etc/EOF\n' ++ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n' ++ 'run \\`npm start\\` and \\$(id) for $USER, \\$(literal) and ${HOME:-\\$(x)}\nE2B_HEREDOC_EOF',+ 'E2B_HEREDOC_DEST=.\n' ++ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n' ++ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n' ++ 'x\nE2B_HEREDOC_EOF',+ ])+ }+)++buildTemplateTest(+ 'fromDockerfile COPY heredoc keeps Docker substitution patterns',+ () => {+ const dockerfile = `FROM node:24+COPY <<EOF /etc/app.conf+\${X/old/new} \${X//o/0} \${X/a\\/b/c} \${X/\`/x} \${Y#\\*} \${Y%%\\}} \${Z:-foo\\}bar} \${Z:-a\\\\b}+EOF`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ 'E2B_HEREDOC_DEST=/etc/app.conf\n' ++ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n' ++ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n' ++ '${X/old/new} ${X//o/0} ${X/a\\/b/c} ${X/\\`/x} ${Y#\\*} ${Y%%\\}} ${Z:-foo\\}bar} ${Z:-a\\\\b}\nE2B_HEREDOC_EOF',+ ])+ }+)++buildTemplateTest(+ 'fromDockerfile COPY --chmod resolves ARG and ENV values',+ () => {+ const dockerfile = `FROM node:24+ARG MODE=440+ENV FULL=0\${MODE}+COPY --chmod=$MODE a /a+COPY --chmod=\${FULL} b /b+COPY --chmod=\${UNSET:-755} c /c`++ const template = Template().fromDockerfile(dockerfile)+ const copies = instructionsOf(template)+ .filter((i) => i.type === InstructionType.COPY)+ .map((i) => i.args)++ assert.deepEqual(copies, [+ ['a', '/a', '', '0440'],+ ['b', '/b', '', '0440'],+ ['c', '/c', '', '0755'],+ ])+ }+)++buildTemplateTest(+ 'fromDockerfile COPY heredoc with a shell-unsafe name',+ () => {+ const dockerfile = `FROM node:24+COPY <<FOO;BAR /etc/+hi+FOO;BAR`++ const template = Template().fromDockerfile(dockerfile)+ const runs = instructionsOf(template)+ .filter((i) => i.type === InstructionType.RUN)+ .map((i) => i.args[0])++ assert.deepEqual(runs, [+ "E2B_HEREDOC_DEST='/etc/FOO;BAR'\n" ++ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_FOO_BAR >"$E2B_HEREDOC_DEST"\n' ++ 'hi\nE2B_HEREDOC_FOO_BAR',+ ])+ }+)++buildTemplateTest(+ 'fromDockerfile COPY with literal paths and zero mode',+ () => {+ const dockerfile = `FROM node:24+COPY "<<EOF" /tmp/+COPY --chmod=000 secret.txt /tmp/`++ const template = Template().fromDockerfile(dockerfile)+ const copies = instructionsOf(template)+ .filter((i) => i.type === InstructionType.COPY)+ .map((i) => i.args)++ assert.deepEqual(copies, [+ ['<<EOF', '/tmp/', '', ''],+ ['secret.txt', '/tmp/', '', '0000'],+ ])+ }+)++buildTemplateTest('fromDockerfile combines ENTRYPOINT and CMD', () => {+ const cases: [string, string | undefined][] = [+ [+ 'ENTRYPOINT ["npm", "run"]\nCMD ["start", "--port 80"]',+ `npm run start '--port 80'`,+ ],+ ['ENTRYPOINT ["npm"]\nCMD run start', `npm /bin/sh -c 'run start'`],+ ['ENTRYPOINT npm start\nCMD ["ignored"]', 'npm start'],+ ['CMD npm start', 'npm start'],+ ['CMD ["npm", "start"]', 'npm start'],+ ['', undefined],+ ['CMD', undefined],+ ['ENTRYPOINT', undefined],+ ]+ for (const [tail, expected] of cases) {+ const template = Template().fromDockerfile(`FROM node:24\n${tail}`)+ // @ts-expect-error - startCmd is not a property of TemplateBuilder+ assert.equal(template.startCmd, expected, tail)+ }+})++buildTemplateTest(+ 'fromDockerfile ignores metadata instructions and flags',+ () => {+ const dockerfile = `FROM --platform=linux/amd64 node:24+EXPOSE 80 443+VOLUME ["/data"]+LABEL maintainer="me"+STOPSIGNAL SIGTERM+HEALTHCHECK NONE+RUN --mount=type=cache,target=/root/.npm npm ci`++ const template = Template().fromDockerfile(dockerfile)+ const instructions = instructionsOf(template)+ assert.equal(instructions[2].type, InstructionType.RUN)+ assert.deepEqual(instructions[2].args, ['npm ci'])+ }+)++buildTemplateTest('fromDockerfile rejects invalid Dockerfiles', () => {+ const cases: [string, RegExp][] = [+ ['', /must contain a FROM/],+ ['RUN echo hi', /must contain a FROM/],+ ['FROM a\nFROM b', /Multi-stage/],+ ['FROM a\nRUN <<EOF\nnever closed', /unterminated heredoc/],+ ['FROM a\nCOPY <<EOF /x\n${}\nEOF', /bad substitution/],+ ['FROM a\nCOPY <<EOF /x\n${HOME:-\nEOF', /missing '}'/],+ ['FROM a\nCOPY <<EOF /x\n${X/a\nEOF', /missing '\/' in \${}/],+ ['FROM a\nCOPY <<EOF /x\n${X:/a/b}\nEOF', /unsupported modifier \(:\/\)/],+ [+ 'FROM a\nCOPY --chmod=$NOPE a b',+ /invalid chmod value "\$NOPE" \(resolves to ""\)/,+ ],+ ['FROM a\nBOGUS instruction', /unknown instruction: BOGUS/],+ ['FROM a\nCOPY --unknown=1 a b', /unknown flag: unknown/],+ ['FROM a\nCOPY --from=builder a b', /--from is not supported/],+ ['FROM a\nCOPY --toString=1 a b', /unknown flag: toString/],+ ['FROM a\nENV K="unterminated', /looking for matching double-quote/],+ ['FROM a\nRUN ["not", 1]', /Only strings are supported/],+ ]+ for (const [dockerfile, expected] of cases) {+ assert.throws(+ () => Template().fromDockerfile(dockerfile),+ DockerfileSyntaxError,+ expected,+ dockerfile+ )+ }+})diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 93c67b65b..14d05ac66 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -133,6 +133,7 @@ from .template.logger import (LogEntryStart,default_build_logger,)+from .template.dockerfile_parser import DockerfileSyntaxErrorfrom .template.main import TemplateBase, TemplateClassfrom .template.readycmd import (ReadyCmd,@@ -194,6 +195,7 @@ __all__ = ["InvalidArgumentException","NotEnoughSpaceException","TemplateException",+ "DockerfileSyntaxError","BuildException","FileUploadException","RateLimitException",diff --git a/packages/python-sdk/e2b/template/dockerfile_parser.py b/packages/python-sdk/e2b/template/dockerfile_parser.pyindex d51bf9e71..1363b3c97 100644--- a/packages/python-sdk/e2b/template/dockerfile_parser.py+++ b/packages/python-sdk/e2b/template/dockerfile_parser.py@@ -1,10 +1,25 @@-import jsonimport osimport re-import tempfile-from typing import Dict, List, Optional, Protocol, Union, Literal--from dockerfile_parse import DockerfileParser+import shlex+from typing import Dict, List, Literal, Mapping, Optional, Protocol, Union++from e2b_dockerfile_utils import (+ DockerfileHeredoc,+ DockerfileInstruction,+ DockerfileSyntaxError,+ ShellLex,+ chomp_heredoc_content,+ parse_dockerfile_ast,+ parse_heredoc,+)+from e2b.template.readycmd import wait_for_timeout++__all__ = [+ "DockerfileParserInterface",+ "DockerfFileFinalParserInterface",+ "DockerfileSyntaxError",+ "parse_dockerfile",+]class DockerfFileFinalParserInterface(Protocol):@@ -52,235 +67,568 @@ class DockerfileParserInterface(Protocol):...-def parse_dockerfile(- dockerfile_content_or_path: str, template_builder: DockerfileParserInterface-) -> str:- """- Parse a Dockerfile and convert it to Template SDK format.+# flag name -> (type, ignored). Ignored flags are accepted with a warning.+FlagSpecs = Mapping[str, "tuple[str, bool]"]- :param dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file- :param template_builder: Interface providing template builder methods+_RUN_FLAGS: FlagSpecs = {+ "mount": ("string", True),+ "network": ("string", True),+ "security": ("string", True),+ "device": ("string", True),+}- :return: The base image from the Dockerfile+_COPY_FLAGS: FlagSpecs = {+ "chown": ("string", False),+ "chmod": ("string", False),+ "from": ("string", False),+ "link": ("bool", True),+ "exclude": ("string", True),+ "parents": ("bool", True),+}- :raises ValueError: If the Dockerfile is invalid or unsupported- """- # Check if input is a file path that exists- if os.path.isfile(dockerfile_content_or_path):- # Read the file content- with open(dockerfile_content_or_path, "r", encoding="utf-8") as f:- dockerfile_content = f.read()- else:- # Treat as content directly- dockerfile_content = dockerfile_content_or_path-- # Use a temporary directory to avoid creating files in the current directory- with tempfile.TemporaryDirectory() as temp_dir:- # Create a temporary Dockerfile- dockerfile_path = os.path.join(temp_dir, "Dockerfile")- with open(dockerfile_path, "w") as f:- f.write(dockerfile_content)-- dfp = DockerfileParser(path=temp_dir)-- # Check for multi-stage builds- from_instructions = [- instruction- for instruction in dfp.structure- if instruction["instruction"] == "FROM"- ]+_ADD_FLAGS: FlagSpecs = {+ **_COPY_FLAGS,+ "keep-git-dir": ("bool", True),+ "checksum": ("string", True),+ "unpack": ("bool", True),+}- if len(from_instructions) > 1:- raise ValueError("Multi-stage Dockerfiles are not supported")+_FROM_FLAGS: FlagSpecs = {+ "platform": ("string", True),+}- if len(from_instructions) == 0:- raise ValueError("Dockerfile must contain a FROM instruction")+# Metadata-only instructions that have no equivalent in a template.+_IGNORED_INSTRUCTIONS = {"EXPOSE", "VOLUME", "LABEL", "MAINTAINER"}- # Set the base image from the first FROM instruction- base_image = from_instructions[0]["value"]- # Remove AS alias if present (e.g., "node:18 AS builder" -> "node:18")- if " as " in base_image.lower():- base_image = base_image.split(" as ")[0].strip()+_CHMOD = re.compile(r"^[0-7]{3,4}$")+_REMOTE_URL = re.compile(r"^[a-z][a-z0-9+.-]*://", re.IGNORECASE)- user_changed = False- workdir_changed = False- # Set the user and workdir to the Docker defaults- template_builder.set_user("root")- template_builder.set_workdir("/")+def _shell_join(words: List[str]) -> str:+ return " ".join(shlex.quote(word) for word in words)- # Process all other instructions- for instruction_data in dfp.structure:- instruction = instruction_data["instruction"]- value = instruction_data["value"]- if instruction == "FROM":- # Already handled above- continue- elif instruction == "RUN":- _handle_run_instruction(value, template_builder)- elif instruction in ["COPY", "ADD"]:- _handle_copy_instruction(value, template_builder)- elif instruction == "WORKDIR":- _handle_workdir_instruction(value, template_builder)- workdir_changed = True- elif instruction == "USER":- _handle_user_instruction(value, template_builder)- user_changed = True- elif instruction in ["ENV", "ARG"]:- _handle_env_instruction(value, instruction, template_builder)- elif instruction in ["CMD", "ENTRYPOINT"]:- _handle_cmd_entrypoint_instruction(value, template_builder)+_VARIABLE_NAME = re.compile(r"\d+|[@*#?\-$!0]|\w+")+++def _shell_literal(ch: str, stop_char: Optional[str] = None) -> str:+ return "\\" + ch if ch in "\\`$" or ch == stop_char else ch+++def _expandable_heredoc_body(content: str, line: int) -> str:+ """Rewrite an expandable heredoc body so that the shell applies Docker's+ rules: ``$VAR`` / ``${VAR...}`` are substituted, a backslash escapes the next+ character, and everything else - ``$(...)`` and backticks included - is literal.+ Backslashes inside ``#``, ``%`` and ``/`` patterns stay significant to the+ shell's pattern matching, as they do for Docker.+ """+ pos = 0++ def missing(stop_char: str) -> DockerfileSyntaxError:+ what = "'/' in ${}" if stop_char == "/" else "'}'"+ return DockerfileSyntaxError(f"syntax error: missing {what}", line)++ def name() -> str:+ nonlocal pos+ match = _VARIABLE_NAME.match(content, pos)+ if match is None:+ return ""+ pos = match.end()+ return match.group(0)++ def variable() -> str:+ nonlocal pos+ if pos >= len(content) or content[pos] != "{":+ var_name = name()+ return "\\$" if var_name == "" else "$" + var_name+ pos += 1+ if pos >= len(content):+ raise missing("}")+ if content[pos] in "{}:":+ raise DockerfileSyntaxError("syntax error: bad substitution", line)+ var_name = name()+ if pos >= len(content):+ raise missing("}")+ modifier = content[pos]+ pos += 1+ if modifier == "}":+ return "${" + var_name + "}"+ if modifier == "/":+ if pos < len(content) and content[pos] == "/":+ modifier += "/"+ pos += 1+ pattern = scan("/", True)+ return "${" + var_name + modifier + pattern + "/" + scan("}", True) + "}"+ if modifier == ":":+ if pos >= len(content):+ raise missing("}")+ modifier += content[pos]+ pos += 1+ op = modifier[-1]+ is_pattern = op in "#%"+ if op not in "+-?#%" or (len(modifier) == 2 and is_pattern):+ raise DockerfileSyntaxError(+ f"unsupported modifier ({modifier}) in substitution", line+ )+ return "${" + var_name + modifier + scan("}", is_pattern) + "}"++ def scan(stop_char: Optional[str], raw_escapes: bool = False) -> str:+ nonlocal pos+ out: List[str] = []+ while pos < len(content):+ ch = content[pos]+ pos += 1+ if ch == stop_char:+ return "".join(out)+ if ch == "\\":+ if pos < len(content):+ nxt = content[pos]+ pos += 1+ out.append(+ "\\" + nxt if raw_escapes else _shell_literal(nxt, stop_char)+ )+ elif ch == "$":+ out.append(variable())+ elif ch == "`":+ out.append("\\`")else:- print(f"Unsupported instruction: {instruction}")- continue+ out.append(ch)+ if stop_char is not None:+ raise missing(stop_char)+ return "".join(out)++ return scan(None)+++def _heredoc_terminator(name: str, content: str) -> str:+ """A heredoc delimiter that does not occur in the content it wraps."""+ terminator = "E2B_HEREDOC_" + re.sub(r"[^A-Za-z0-9_]", "_", name)+ while terminator in content:+ terminator += "_"+ return terminator+++def _with_trailing_newline(content: str) -> str:+ if content == "" or content.endswith("\n"):+ return content+ return content + "\n"+++class _StartCommand:+ def __init__(self, json: bool, args: List[str]) -> None:+ self.json = json+ self.args = args+++class _DockerfileConverter:+ def __init__(+ self, template_builder: DockerfileParserInterface, escape_token: str+ ) -> None:+ self._template_builder = template_builder+ self._lex = ShellLex(escape_token)+ self._vars: Dict[str, str] = {}+ # Expands the ARG / ENV values declared earlier in the Dockerfile.+ self._env_lex = ShellLex(escape_token, env=self._vars, skip_unset_env=False)+ self._user_changed = False+ self._workdir_changed = False+ self._cmd: Optional[_StartCommand] = None+ self._entrypoint: Optional[_StartCommand] = None++ def convert(self, instructions: List[DockerfileInstruction]) -> str:+ from_instructions = [i for i in instructions if i.name == "FROM"]+ if len(from_instructions) > 1:+ raise DockerfileSyntaxError("Multi-stage Dockerfiles are not supported")+ if not from_instructions:+ raise DockerfileSyntaxError("Dockerfile must contain a FROM instruction")++ from_instruction = from_instructions[0]+ base_image = self._handle_from(from_instruction)++ # Set the user and workdir to the Docker defaults+ self._template_builder.set_user("root")+ self._template_builder.set_workdir("/")- # Set the user and workdir to the E2B defaults- if not user_changed:- template_builder.set_user("user")- if not workdir_changed:- template_builder.set_workdir("/home/user")-- return base_image---def _handle_run_instruction(- value: str, template_builder: DockerfileParserInterface-) -> None:- """Handle RUN instruction"""- if not value.strip():- return- # Remove line continuations and normalize whitespace- command = re.sub(r"\\\s*\n\s*", " ", value).strip()- template_builder.run_cmd(command)---def _handle_copy_instruction(- value: str, template_builder: DockerfileParserInterface-) -> None:- """Handle COPY/ADD instruction"""- if not value.strip():- return- # Parse source and destination from COPY/ADD command- # Handle both quoted and unquoted paths- parts = []- current_part = ""- in_quotes = False- quote_char = None-- i = 0- while i < len(value):- char = value[i]- if char in ['"', "'"] and (i == 0 or value[i - 1] != "\\"):- if not in_quotes:- in_quotes = True- quote_char = char- elif char == quote_char:- in_quotes = False- quote_char = None+ for instruction in instructions:+ if instruction.name == "FROM":+ continue+ if (+ instruction.start_line < from_instruction.start_line+ and instruction.name != "ARG"+ ):+ raise DockerfileSyntaxError(+ f"{instruction.name} must be preceded by a FROM instruction",+ instruction.start_line,+ )+ self._handle_instruction(instruction)++ self._apply_start_cmd()++ # Set the user and workdir to the E2B defaults+ if not self._user_changed:+ self._template_builder.set_user("user")+ if not self._workdir_changed:+ self._template_builder.set_workdir("/home/user")++ return base_image++ def _handle_instruction(self, instruction: DockerfileInstruction) -> None:+ name = instruction.name+ if name == "RUN":+ self._handle_run(instruction)+ elif name == "COPY":+ self._handle_copy(instruction, _COPY_FLAGS)+ elif name == "ADD":+ self._handle_copy(instruction, _ADD_FLAGS)+ elif name == "WORKDIR":+ self._template_builder.set_workdir(self._expand_single(instruction))+ self._workdir_changed = True+ elif name == "USER":+ self._template_builder.set_user(self._expand_single(instruction))+ self._user_changed = True+ elif name == "ENV":+ self._handle_env(instruction)+ elif name == "ARG":+ self._handle_arg(instruction)+ elif name == "CMD":+ self._parse_flags(instruction, {})+ self._cmd = _StartCommand(instruction.json, instruction.args)+ elif name == "ENTRYPOINT":+ self._parse_flags(instruction, {})+ self._entrypoint = _StartCommand(instruction.json, instruction.args)+ elif name not in _IGNORED_INSTRUCTIONS:+ print(f"Unsupported instruction: {name}")++ def _expand(+ self,+ instruction: DockerfileInstruction,+ word: str,+ lex: Optional[ShellLex] = None,+ ) -> str:+ """Resolve quotes and escapes in a word, keeping ``$VAR`` references."""+ try:+ return (lex or self._lex).process_word(word)+ except ValueError as err:+ raise DockerfileSyntaxError(str(err), instruction.start_line) from None++ def _expand_single(self, instruction: DockerfileInstruction) -> str:+ self._parse_flags(instruction, {})+ if len(instruction.args) != 1:+ raise DockerfileSyntaxError(+ f"{instruction.name} requires exactly one argument",+ instruction.start_line,+ )+ return self._expand(instruction, instruction.args[0])++ def _parse_flags(+ self, instruction: DockerfileInstruction, specs: FlagSpecs+ ) -> Dict[str, str]:+ values: Dict[str, str] = {}+ for flag in instruction.flags:+ if not flag.startswith("--"):+ raise DockerfileSyntaxError(+ f"arg should start with -- : {flag}", instruction.start_line+ )+ body = flag[2:]+ name, sep, raw_value = body.partition("=")+ has_value = sep == "="++ spec = specs.get(name)+ if spec is None:+ raise DockerfileSyntaxError(+ f"unknown flag: {name}", instruction.start_line+ )+ if name in values:+ raise DockerfileSyntaxError(+ f"duplicate flag specified: {name}", instruction.start_line+ )++ flag_type, ignored = spec+ if flag_type == "bool":+ if not has_value or raw_value in ("", "true"):+ value = "true"+ elif raw_value == "false":+ value = "false"+ else:+ raise DockerfileSyntaxError(+ f"expecting boolean value for flag {name}, not: {raw_value}",+ instruction.start_line,+ )else:- current_part += char- elif char == " " and not in_quotes:- if current_part:- parts.append(current_part)- current_part = ""+ if not has_value:+ raise DockerfileSyntaxError(+ f"missing a value on flag: {name}", instruction.start_line+ )+ value = raw_value++ if ignored:+ print(+ f"Ignoring unsupported {instruction.name} flag --{name} "+ f"(line {instruction.start_line})"+ )+ continue+ values[name] = value+ return values++ def _handle_from(self, instruction: DockerfileInstruction) -> str:+ self._parse_flags(instruction, _FROM_FLAGS)+ args = instruction.args+ if len(args) == 3 and args[1].lower() == "as":+ pass # stage alias is irrelevant for a single-stage build+ elif len(args) != 1:+ raise DockerfileSyntaxError(+ "FROM requires either one or three arguments",+ instruction.start_line,+ )+ return self._expand(instruction, args[0])++ def _handle_run(self, instruction: DockerfileInstruction) -> None:+ self._parse_flags(instruction, _RUN_FLAGS)+ args = instruction.args+ if not args:+ raise DockerfileSyntaxError(+ "RUN requires at least one argument", instruction.start_line+ )++ if instruction.json:+ command = _shell_join(args)+ elif instruction.heredocs:+ command = self._run_with_heredocs(args[0], instruction.heredocs)else:- current_part += char- i += 1-- if current_part:- parts.append(current_part)-- # Extract --chown flag and separate from paths- user = None- non_flag_parts = []- for part in parts:- if part.startswith("--chown="):- user = part[8:] # Extract value after "--chown="- elif not part.startswith("--"):- non_flag_parts.append(part)-- if len(non_flag_parts) >= 2:- dest = non_flag_parts[-1] # Last part is destination- sources = non_flag_parts[:-1]-- for src in sources:- template_builder.copy(src, dest, user=user)---def _handle_workdir_instruction(- value: str, template_builder: DockerfileParserInterface-) -> None:- """Handle WORKDIR instruction"""- if not value.strip():- return- workdir = value.strip()- template_builder.set_workdir(workdir)---def _handle_user_instruction(- value: str, template_builder: DockerfileParserInterface-) -> None:- """Handle USER instruction"""- if not value.strip():- return- user = value.strip()- template_builder.set_user(user)---def _handle_env_instruction(- value: str, instruction_type: str, template_builder: DockerfileParserInterface-) -> None:- """Handle ENV/ARG instruction"""- if not value.strip():- return-- # Parse environment variables from the value- # Handle both "KEY=value" and "KEY value" formats- env_vars = {}-- # First try to split on = for KEY=value format- if "=" in value:- # Handle multiple KEY=value pairs on one line- pairs = re.findall(r"(\w+)=([^\s]*(?:\s+(?!\w+=)[^\s]*)*)", value)- for key, val in pairs:- env_vars[key] = val.strip("\"'")- else:- # Handle "KEY value" format- parts = value.split(None, 1)- if len(parts) == 2:- key, val = parts- env_vars[key] = val.strip("\"'")- elif len(parts) == 1 and instruction_type == "ARG":- # ARG without default value- key = parts[0]- env_vars[key] = ""-- # Add each environment variable- if env_vars:- template_builder.set_envs(env_vars)---def _handle_cmd_entrypoint_instruction(- value: str, template_builder: DockerfileParserInterface-) -> None:- """Handle CMD/ENTRYPOINT instruction - convert to set_start_cmd with 20s timeout"""- if not value.strip():- return- command = value.strip()-- # Try to parse as JSON (for array format like CMD ["sleep", "infinity"])+ command = args[0]+ self._template_builder.run_cmd(command)++ @staticmethod+ def _run_with_heredocs(line: str, heredocs: List[DockerfileHeredoc]) -> str:+ def heredoc_content(heredoc: DockerfileHeredoc) -> str:+ if heredoc.chomp:+ return chomp_heredoc_content(heredoc.content)+ return heredoc.content++ # `RUN <<EOF` on its own: the heredoc body is the script itself.+ if len(heredocs) == 1 and parse_heredoc(line.strip()) is not None:+ heredoc = heredocs[0]+ content = heredoc_content(heredoc)+ if not content.startswith("#!"):+ return content+ # A shebang script: write it to a temporary file and execute it.+ script = shlex.quote(f"/tmp/{heredoc.name}")+ terminator = _heredoc_terminator(heredoc.name, content)+ return (+ f"cat <<'{terminator}' >{script}\n"+ + _with_trailing_newline(content)+ + f"{terminator}\n"+ + f"chmod +x {script} && {script}\n"+ + f"E2B_EXIT=$?; rm -f {script}; exit $E2B_EXIT"+ )++ # Heredocs used as part of a larger command (`cat <<EOF > file`,+ # `python3 <<EOF`): rebuild the heredoc so the shell handles it.+ full = line+ for heredoc in heredocs:+ full += "\n" + heredoc.content + heredoc.name+ return full++ def _handle_copy(+ self, instruction: DockerfileInstruction, specs: FlagSpecs+ ) -> None:+ flags = self._parse_flags(instruction, specs)+ if len(instruction.args) < 2:+ raise DockerfileSyntaxError(+ f"{instruction.name} requires at least two arguments",+ instruction.start_line,+ )+ if "from" in flags:+ raise DockerfileSyntaxError(+ f"{instruction.name} --from is not supported "+ "(multi-stage builds are not supported)",+ instruction.start_line,+ )++ user = self._expand(instruction, flags["chown"]) if "chown" in flags else None+ mode: Optional[int] = None+ if "chmod" in flags:+ chmod = self._expand(instruction, flags["chmod"])+ resolved = self._expand(instruction, flags["chmod"], self._env_lex)+ if not _CHMOD.match(resolved):+ detail = "" if resolved == chmod else f' (resolves to "{resolved}")'+ raise DockerfileSyntaxError(+ f'invalid chmod value "{chmod}"{detail}, '+ "expected an octal mode such as 0755",+ instruction.start_line,+ )+ mode = int(resolved, 8)++ # Heredoc markers are recognized on the raw tokens, like the AST does:+ # a quoted `"<<EOF"` is a literal file name, not a heredoc.+ raw_dest = instruction.args[-1]+ if parse_heredoc(raw_dest) is not None:+ raise DockerfileSyntaxError(+ f"{instruction.name} cannot accept a heredoc as a destination",+ instruction.start_line,+ )+ dest = self._expand(instruction, raw_dest)++ heredocs_by_name = {heredoc.name: heredoc for heredoc in instruction.heredocs}++ for raw_src in instruction.args[:-1]:+ heredoc = parse_heredoc(raw_src)+ if heredoc is not None:+ content = heredocs_by_name.get(heredoc.name)+ if content is None:+ raise DockerfileSyntaxError(+ f"missing heredoc content for {heredoc.name}",+ instruction.start_line,+ )+ self._copy_heredoc(content, dest, user, mode, instruction.start_line)+ continue+ src = self._expand(instruction, raw_src)+ if instruction.name == "ADD" and _REMOTE_URL.match(src):+ raise DockerfileSyntaxError(+ f"ADD from a remote URL is not supported: {src}",+ instruction.start_line,+ )+ self._template_builder.copy(src, dest, user=user, mode=mode)++ def _copy_heredoc(+ self,+ heredoc: DockerfileHeredoc,+ dest: str,+ user: Optional[str],+ mode: Optional[int],+ line: int,+ ) -> None:+ """``COPY <<EOF /path`` writes the heredoc body to a file inside the sandbox."""+ content = (+ chomp_heredoc_content(heredoc.content) if heredoc.chomp else heredoc.content+ )+ if heredoc.expand:+ content = _expandable_heredoc_body(content, line)+ plain_terminator = _heredoc_terminator(heredoc.name, content)+ terminator = plain_terminator if heredoc.expand else f"'{plain_terminator}'"+ target = '"$E2B_HEREDOC_DEST"'++ # Like Docker, a dest that is a directory receives a file named after the heredoc.+ if dest.endswith("/"):+ command = f"E2B_HEREDOC_DEST={shlex.quote(dest + heredoc.name)}\n"+ else:+ command = (+ f"E2B_HEREDOC_DEST={shlex.quote(dest)}\n"+ f"if [ -d {target} ]; then E2B_HEREDOC_DEST={target}/{shlex.quote(heredoc.name)}; fi\n"+ )+ command += (+ f'mkdir -p "$(dirname {target})" && cat <<{terminator} >{target}\n'+ + _with_trailing_newline(content)+ + plain_terminator+ )+ if user is not None:+ command += f"\nchown {shlex.quote(user)} {target}"+ if mode is not None:+ command += f"\nchmod {mode:o} {target}"+ # COPY writes as the builder (root), independent of the current USER.+ self._template_builder.run_cmd(command, user="root")++ def _handle_env(self, instruction: DockerfileInstruction) -> None:+ self._parse_flags(instruction, {})+ args = instruction.args+ if not args:+ raise DockerfileSyntaxError(+ "ENV requires at least one argument", instruction.start_line+ )+ envs: Dict[str, str] = {}+ for i in range(0, len(args) - 2, 3):+ key = self._expand(instruction, args[i])+ if key == "":+ raise DockerfileSyntaxError(+ "ENV names can not be blank", instruction.start_line+ )+ envs[key] = self._expand(instruction, args[i + 1])+ self._vars[key] = self._expand(instruction, args[i + 1], self._env_lex)+ self._template_builder.set_envs(envs)++ def _handle_arg(self, instruction: DockerfileInstruction) -> None:+ self._parse_flags(instruction, {})+ args = instruction.args+ if not args:+ raise DockerfileSyntaxError(+ "ARG requires at least one argument", instruction.start_line+ )+ envs: Dict[str, str] = {}+ for arg in args:+ name, sep, value = arg.partition("=")+ key = self._expand(instruction, name)+ if key == "":+ raise DockerfileSyntaxError(+ "ARG names can not be blank", instruction.start_line+ )+ envs[key] = self._expand(instruction, value) if sep else ""+ self._vars[key] = (+ self._expand(instruction, value, self._env_lex) if sep else ""+ )+ self._template_builder.set_envs(envs)++ def _apply_start_cmd(self) -> None:+ """+ Combine ENTRYPOINT and CMD following Docker's rules:+ - exec-form ENTRYPOINT gets CMD appended as arguments+ (a shell-form CMD is appended as ``/bin/sh -c <cmd>``),+ - shell-form ENTRYPOINT ignores CMD,+ - without ENTRYPOINT the CMD is used as-is.+ """+ cmd = self._cmd+ entrypoint = self._entrypoint+ command: Optional[str] = None++ if entrypoint is not None:+ if entrypoint.json:+ words = list(entrypoint.args)+ if cmd is not None:+ if cmd.json:+ words.extend(cmd.args)+ elif cmd.args:+ words.extend(["/bin/sh", "-c", cmd.args[0]])+ command = _shell_join(words) if words else None+ else:+ command = entrypoint.args[0] if entrypoint.args else None+ elif cmd is not None:+ if cmd.json:+ command = _shell_join(cmd.args) if cmd.args else None+ else:+ command = cmd.args[0] if cmd.args else None++ if command is not None and command.strip() != "":+ self._template_builder.set_start_cmd(command, wait_for_timeout(20_000))+++def _read_dockerfile(dockerfile_content_or_path: str) -> str:try:- parsed_command = json.loads(command)- if isinstance(parsed_command, list):- command = " ".join(str(item) for item in parsed_command)- except Exception:+ if os.path.isfile(dockerfile_content_or_path):+ with open(dockerfile_content_or_path, "r", encoding="utf-8") as f:+ return f.read()+ except (OSError, ValueError):+ # If there's any error checking the file, treat as contentpass+ return dockerfile_content_or_path+++def parse_dockerfile(+ dockerfile_content_or_path: str, template_builder: DockerfileParserInterface+) -> str:+ """+ Parse a Dockerfile and convert it to Template SDK format.++ :param dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file+ :param template_builder: Interface providing template builder methods++ :return: The base image from the Dockerfile++ :raises ValueError: If the Dockerfile is invalid or unsupported+ """+ dockerfile_content = _read_dockerfile(dockerfile_content_or_path)+ ast = parse_dockerfile_ast(dockerfile_content)- # Import wait_for_timeout locally to avoid circular dependency- def wait_for_timeout(timeout: int) -> str:- # convert to seconds, but ensure minimum of 1 second- seconds = max(1, timeout // 1000)- return f"sleep {seconds}"+ for warning in ast.warnings:+ print(f"{warning.message} (line {warning.line})")- template_builder.set_start_cmd(command, wait_for_timeout(20_000))+ return _DockerfileConverter(template_builder, ast.escape_token).convert(+ ast.instructions+ )diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.pyindex 5cf259a43..98d642301 100644--- a/packages/python-sdk/e2b/template/main.py+++ b/packages/python-sdk/e2b/template/main.py@@ -84,7 +84,7 @@ class TemplateBuilder:src_string,str(dest),user or "",- pad_octal(mode) if mode else "",+ pad_octal(mode) if mode is not None else "",]instruction: Instruction = {@@ -232,7 +232,7 @@ class TemplateBuilder:"""path_list = [path] if isinstance(path, (str, Path)) else pathargs = ["mkdir", "-p"]- if mode:+ if mode is not None:args.append(f"-m {pad_octal(mode)}")args.extend([shlex.quote(str(p)) for p in path_list])diff --git a/packages/python-sdk/e2b/template/utils.py b/packages/python-sdk/e2b/template/utils.pyindex 9c9757818..bf153bc6a 100644--- a/packages/python-sdk/e2b/template/utils.py+++ b/packages/python-sdk/e2b/template/utils.py@@ -13,7 +13,7 @@ from typing import IO, List, Optional, Unionfrom e2b.exceptions import TemplateExceptionfrom e2b.template.consts import BASE_STEP_NAME, FINALIZE_STEP_NAME-from e2b.template.dockerignore import PatternMatcher+from e2b_dockerfile_utils import PatternMatcherdef make_traceback(caller_frame: Optional[FrameType]) -> Optional[TracebackType]:@@ -122,7 +122,7 @@ def read_dockerignore(context_path: str) -> List[str]:return [line.strip()for line in content.split("\n")- if line.strip() and not line.strip().startswith("#")+ if not line.startswith("#") and line.strip()]@@ -188,9 +188,13 @@ def get_all_files_in_path(files = set()abs_context_path = os.path.abspath(context_path)- matcher = PatternMatcher(- [_normalize_ignore_pattern(p, abs_context_path) for p in ignore_patterns]- )+ try:+ matcher = PatternMatcher(+ [_normalize_ignore_pattern(p, abs_context_path) for p in ignore_patterns],+ backslash_is_separator=os.sep == "\\",+ )+ except ValueError as e:+ raise TemplateException(str(e)) from edef walk(dir_path: str, dir_relative_path: str) -> None:with os.scandir(dir_path) as entries:diff --git a/packages/python-sdk/package.json b/packages/python-sdk/package.jsonindex 371ce6b51..beb57be68 100644--- a/packages/python-sdk/package.json+++ b/packages/python-sdk/package.json@@ -2,6 +2,9 @@"name": "@e2b/python-sdk","private": true,"version": "2.53.1",+ "dependencies": {+ "@e2b/dockerfile-utils-python": "workspace:*"+ },"scripts": {"test": "uv run pytest -n 4 --verbose -x","postVersion": "uv version --frozen $(pnpm pkg get version --workspaces=false | tr -d \\\")",diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.tomlindex 39e6b8ecf..52b3cc140 100644--- a/packages/python-sdk/pyproject.toml+++ b/packages/python-sdk/pyproject.toml@@ -17,10 +17,10 @@ dependencies = [# 4.10 is the first release whose TypedDict accepts PEP 728's `closed`,# which the generated e2b/sandbox/mcp.py passes at class-creation time."typing-extensions>=4.10.0",- "dockerfile-parse>=2.0.1,<3","rich>=14.0.0","connectrpc>=0.11.1,<0.12","pyqwest>=0.10.0,<0.11",+ "e2b-dockerfile-utils>=0.1.0,<0.2",][project.urls]@@ -61,6 +61,9 @@ build-backend = "uv_build"module-name = ["e2b"]module-root = ""+[tool.uv.sources]+e2b-dockerfile-utils = { path = "../dockerfile-utils-python", editable = true }+[tool.basedpyright]reportInconsistentOverload = falsediff --git a/packages/python-sdk/tests/async/template_async/methods/test_from_dockerfile.py b/packages/python-sdk/tests/async/template_async/methods/test_from_dockerfile.pyindex 1c9f2fda0..f164b1b17 100644--- a/packages/python-sdk/tests/async/template_async/methods/test_from_dockerfile.py+++ b/packages/python-sdk/tests/async/template_async/methods/test_from_dockerfile.py@@ -1,6 +1,6 @@import pytest-from e2b import AsyncTemplate+from e2b import DockerfileSyntaxError, AsyncTemplatefrom e2b.template.types import InstructionType@@ -131,3 +131,355 @@ COPY --chown=anotheruser config.json /config/"""assert (copy_instruction2["args"][2] == "anotheruser") # user from --chown (without group)+++def _instructions(template):+ return template._template._instructions++[email protected]_debug()+async def test_from_dockerfile_with_quoted_env_and_arg_values():+ dockerfile = """FROM node:24+ENV A="hello world" B='single quoted' C=plain D=escaped\\ space+ENV LEGACY some value with spaces+ENV MULTI=1 \\+ # comment inside continuation+ LINE="two \\+words"+ARG VERSION=1.0 NAME="with space" EMPTY+ENV REF="$HOME/bin:${PATH}\""""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ envs = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.ENV+ ]++ assert envs == [+ ["A", "hello world", "B", "single quoted", "C", "plain", "D", "escaped space"],+ ["LEGACY", "some value with spaces"],+ ["MULTI", "1", "LINE", "two words"],+ ["VERSION", "1.0", "NAME", "with space", "EMPTY", ""],+ ["REF", "$HOME/bin:${PATH}"],+ ]++[email protected]_debug()+async def test_from_dockerfile_with_mixed_case_keywords_and_as_alias():+ dockerfile = """from node:24 As Builder+run echo hi+Workdir /app+uSeR node"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ assert template._template._base_image == "node:24"+ instructions = _instructions(template)+ assert instructions[2]["type"] == InstructionType.RUN+ assert instructions[2]["args"] == ["echo hi"]+ assert instructions[3]["args"] == ["/app"]+ assert instructions[4]["args"] == ["node"]++[email protected]_debug()+async def test_from_dockerfile_preserves_whitespace_in_run_and_uses_shell_form():+ dockerfile = """FROM node:24+RUN echo "a b" && \\+ echo 'c d'+RUN ["echo", "hello world", "it's"]"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ """echo "a b" && echo 'c d'""",+ """echo 'hello world' 'it'"'"'s'""",+ ]++[email protected]_debug()+async def test_from_dockerfile_with_escape_directive():+ dockerfile = """# escape=`+FROM node:24+RUN echo one `+ && echo two+ENV P="C:\\tools\""""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ instructions = _instructions(template)+ assert instructions[2]["args"] == ["echo one && echo two"]+ assert instructions[3]["args"] == ["P", "C:\\tools"]++[email protected]_debug()+async def test_from_dockerfile_with_copy_chmod_and_quoted_paths():+ dockerfile = """FROM node:24+COPY --chmod=755 --chown=app:app "my file.txt" other.txt /dest/+COPY ["json file.txt", "/dest/"]+ADD archive.tar.gz /opt/"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["my file.txt", "/dest/", "app:app", "0755"],+ ["other.txt", "/dest/", "app:app", "0755"],+ ["json file.txt", "/dest/", "", ""],+ ["archive.tar.gz", "/opt/", "", ""],+ ]++[email protected]_debug()+async def test_from_dockerfile_with_heredocs():+ dockerfile = """FROM node:24+RUN <<EOF+npm install+npm run build+EOF+RUN <<-EOT+\techo tabbed+EOT+RUN python3 - <<PY+print("hi")+PY+RUN 3<<FD+touch /tmp/fd+FD+COPY <<'CONF' /etc/app.conf+key=$VALUE+CONF"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "npm install\nnpm run build\n",+ "echo tabbed\n",+ 'python3 - <<PY\nprint("hi")\nPY',+ "touch /tmp/fd\n",+ """E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/CONF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<'E2B_HEREDOC_CONF' >"$E2B_HEREDOC_DEST"\nkey=$VALUE\nE2B_HEREDOC_CONF""",+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_heredoc_runs_as_root():+ dockerfile = """FROM node:24+USER app+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF+x=1+EOF"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ [+ 'E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF_ >"$E2B_HEREDOC_DEST"\n'+ "E2B_HEREDOC_EOF\nx=1\nE2B_HEREDOC_EOF_",+ "root",+ ],+ ]++[email protected]_debug()+async def test_from_dockerfile_heredoc_terminator_avoids_the_content():+ dockerfile = """FROM node:24+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_+E2B_HEREDOC_EOF+EOF"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ 'E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF____ >"$E2B_HEREDOC_DEST"\n'+ "E2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_\nE2B_HEREDOC_EOF\nE2B_HEREDOC_EOF____",+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_heredoc_keeps_docker_substitution_patterns():+ dockerfile = """FROM node:24+COPY <<EOF /etc/app.conf+${X/old/new} ${X//o/0} ${X/a\\/b/c} ${X/`/x} ${Y#\\*} ${Y%%\\}} ${Z:-foo\\}bar} ${Z:-a\\\\b}+EOF"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST=/etc/app.conf\n"+ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n'+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "${X/old/new} ${X//o/0} ${X/a\\/b/c} ${X/\\`/x} ${Y#\\*} ${Y%%\\}} ${Z:-foo\\}bar} ${Z:-a\\\\b}\nE2B_HEREDOC_EOF",+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_chmod_resolves_arg_and_env_values():+ dockerfile = """FROM node:24+ARG MODE=440+ENV FULL=0${MODE}+COPY --chmod=$MODE a /a+COPY --chmod=${FULL} b /b+COPY --chmod=${UNSET:-755} c /c"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["a", "/a", "", "0440"],+ ["b", "/b", "", "0440"],+ ["c", "/c", "", "0755"],+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_heredoc_with_shell_unsafe_name():+ dockerfile = """FROM node:24+COPY <<FOO;BAR /etc/+hi+FOO;BAR"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST='/etc/FOO;BAR'\n"+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_FOO_BAR >"$E2B_HEREDOC_DEST"\n'+ "hi\nE2B_HEREDOC_FOO_BAR",+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_heredoc_into_directory_expands_only_variables():+ dockerfile = """FROM node:24+COPY <<EOF /etc/+run `npm start` and $(id) for $USER, \\$(literal) and ${HOME:-$(x)}+EOF+COPY <<EOF .+x+EOF"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST=/etc/EOF\n"+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "run \\`npm start\\` and \\$(id) for $USER, \\$(literal) and ${HOME:-\\$(x)}\nE2B_HEREDOC_EOF",+ "E2B_HEREDOC_DEST=.\n"+ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n'+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "x\nE2B_HEREDOC_EOF",+ ]++[email protected]_debug()+async def test_from_dockerfile_copy_with_literal_paths_and_zero_mode():+ dockerfile = """FROM node:24+COPY "<<EOF" /tmp/+COPY --chmod=000 secret.txt /tmp/"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["<<EOF", "/tmp/", "", ""],+ ["secret.txt", "/tmp/", "", "0000"],+ ]++[email protected]_debug()+async def test_from_dockerfile_combines_entrypoint_and_cmd():+ cases = [+ (+ 'ENTRYPOINT ["npm", "run"]\nCMD ["start", "--port 80"]',+ "npm run start '--port 80'",+ ),+ ('ENTRYPOINT ["npm"]\nCMD run start', "npm /bin/sh -c 'run start'"),+ ('ENTRYPOINT npm start\nCMD ["ignored"]', "npm start"),+ ("CMD npm start", "npm start"),+ ('CMD ["npm", "start"]', "npm start"),+ ("", None),+ ("CMD", None),+ ("ENTRYPOINT", None),+ ]+ for tail, expected in cases:+ template = AsyncTemplate().from_dockerfile(f"FROM node:24\n{tail}")+ assert template._template._start_cmd == expected, tail++[email protected]_debug()+async def test_from_dockerfile_ignores_metadata_instructions_and_flags():+ dockerfile = """FROM --platform=linux/amd64 node:24+EXPOSE 80 443+VOLUME ["/data"]+LABEL maintainer="me"+STOPSIGNAL SIGTERM+HEALTHCHECK NONE+RUN --mount=type=cache,target=/root/.npm npm ci"""++ template = AsyncTemplate().from_dockerfile(dockerfile)+ instructions = _instructions(template)+ assert instructions[2]["type"] == InstructionType.RUN+ assert instructions[2]["args"] == ["npm ci"]++[email protected]_debug()+async def test_from_dockerfile_rejects_invalid_dockerfiles():+ cases = [+ ("", "must contain a FROM"),+ ("RUN echo hi", "must contain a FROM"),+ ("FROM a\nFROM b", "Multi-stage"),+ ("FROM a\nRUN <<EOF\nnever closed", "unterminated heredoc"),+ ("FROM a\nCOPY <<EOF /x\n${}\nEOF", "bad substitution"),+ ("FROM a\nCOPY <<EOF /x\n${HOME:-\nEOF", "missing '}'"),+ ("FROM a\nCOPY <<EOF /x\n${X/a\nEOF", r"missing '/' in \$\{\}"),+ ("FROM a\nCOPY <<EOF /x\n${X:/a/b}\nEOF", r"unsupported modifier \(:/\)"),+ (+ "FROM a\nCOPY --chmod=$NOPE a b",+ r'invalid chmod value "\$NOPE" \(resolves to ""\)',+ ),+ ("FROM a\nBOGUS instruction", "unknown instruction: BOGUS"),+ ("FROM a\nCOPY --unknown=1 a b", "unknown flag: unknown"),+ ("FROM a\nCOPY --from=builder a b", "--from is not supported"),+ ("FROM a\nCOPY --toString=1 a b", "unknown flag: toString"),+ ('FROM a\nENV K="unterminated', "looking for matching double-quote"),+ ('FROM a\nRUN ["not", 1]', "Only strings are supported"),+ ]+ for dockerfile, expected in cases:+ with pytest.raises(DockerfileSyntaxError, match=expected):+ AsyncTemplate().from_dockerfile(dockerfile)diff --git a/packages/python-sdk/tests/sync/template_sync/methods/test_from_dockerfile.py b/packages/python-sdk/tests/sync/template_sync/methods/test_from_dockerfile.pyindex a1db51acf..cb1dbcc46 100644--- a/packages/python-sdk/tests/sync/template_sync/methods/test_from_dockerfile.py+++ b/packages/python-sdk/tests/sync/template_sync/methods/test_from_dockerfile.py@@ -1,6 +1,6 @@import pytest-from e2b import Template+from e2b import DockerfileSyntaxError, Templatefrom e2b.template.types import InstructionType@@ -131,3 +131,355 @@ COPY --chown=anotheruser config.json /config/"""assert (copy_instruction2["args"][2] == "anotheruser") # user from --chown (without group)+++def _instructions(template):+ return template._template._instructions++[email protected]_debug()+def test_from_dockerfile_with_quoted_env_and_arg_values():+ dockerfile = """FROM node:24+ENV A="hello world" B='single quoted' C=plain D=escaped\\ space+ENV LEGACY some value with spaces+ENV MULTI=1 \\+ # comment inside continuation+ LINE="two \\+words"+ARG VERSION=1.0 NAME="with space" EMPTY+ENV REF="$HOME/bin:${PATH}\""""++ template = Template().from_dockerfile(dockerfile)+ envs = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.ENV+ ]++ assert envs == [+ ["A", "hello world", "B", "single quoted", "C", "plain", "D", "escaped space"],+ ["LEGACY", "some value with spaces"],+ ["MULTI", "1", "LINE", "two words"],+ ["VERSION", "1.0", "NAME", "with space", "EMPTY", ""],+ ["REF", "$HOME/bin:${PATH}"],+ ]++[email protected]_debug()+def test_from_dockerfile_with_mixed_case_keywords_and_as_alias():+ dockerfile = """from node:24 As Builder+run echo hi+Workdir /app+uSeR node"""++ template = Template().from_dockerfile(dockerfile)+ assert template._template._base_image == "node:24"+ instructions = _instructions(template)+ assert instructions[2]["type"] == InstructionType.RUN+ assert instructions[2]["args"] == ["echo hi"]+ assert instructions[3]["args"] == ["/app"]+ assert instructions[4]["args"] == ["node"]++[email protected]_debug()+def test_from_dockerfile_preserves_whitespace_in_run_and_uses_shell_form():+ dockerfile = """FROM node:24+RUN echo "a b" && \\+ echo 'c d'+RUN ["echo", "hello world", "it's"]"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ """echo "a b" && echo 'c d'""",+ """echo 'hello world' 'it'"'"'s'""",+ ]++[email protected]_debug()+def test_from_dockerfile_with_escape_directive():+ dockerfile = """# escape=`+FROM node:24+RUN echo one `+ && echo two+ENV P="C:\\tools\""""++ template = Template().from_dockerfile(dockerfile)+ instructions = _instructions(template)+ assert instructions[2]["args"] == ["echo one && echo two"]+ assert instructions[3]["args"] == ["P", "C:\\tools"]++[email protected]_debug()+def test_from_dockerfile_with_copy_chmod_and_quoted_paths():+ dockerfile = """FROM node:24+COPY --chmod=755 --chown=app:app "my file.txt" other.txt /dest/+COPY ["json file.txt", "/dest/"]+ADD archive.tar.gz /opt/"""++ template = Template().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["my file.txt", "/dest/", "app:app", "0755"],+ ["other.txt", "/dest/", "app:app", "0755"],+ ["json file.txt", "/dest/", "", ""],+ ["archive.tar.gz", "/opt/", "", ""],+ ]++[email protected]_debug()+def test_from_dockerfile_with_heredocs():+ dockerfile = """FROM node:24+RUN <<EOF+npm install+npm run build+EOF+RUN <<-EOT+\techo tabbed+EOT+RUN python3 - <<PY+print("hi")+PY+RUN 3<<FD+touch /tmp/fd+FD+COPY <<'CONF' /etc/app.conf+key=$VALUE+CONF"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "npm install\nnpm run build\n",+ "echo tabbed\n",+ 'python3 - <<PY\nprint("hi")\nPY',+ "touch /tmp/fd\n",+ """E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/CONF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<'E2B_HEREDOC_CONF' >"$E2B_HEREDOC_DEST"\nkey=$VALUE\nE2B_HEREDOC_CONF""",+ ]++[email protected]_debug()+def test_from_dockerfile_copy_heredoc_runs_as_root():+ dockerfile = """FROM node:24+USER app+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF+x=1+EOF"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ [+ 'E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF_ >"$E2B_HEREDOC_DEST"\n'+ "E2B_HEREDOC_EOF\nx=1\nE2B_HEREDOC_EOF_",+ "root",+ ],+ ]++[email protected]_debug()+def test_from_dockerfile_heredoc_terminator_avoids_the_content():+ dockerfile = """FROM node:24+COPY <<EOF /etc/app.conf+E2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_+E2B_HEREDOC_EOF+EOF"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ 'E2B_HEREDOC_DEST=/etc/app.conf\nif [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\nmkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF____ >"$E2B_HEREDOC_DEST"\n'+ "E2B_HEREDOC_EOF___ E2B_HEREDOC_EOF_\nE2B_HEREDOC_EOF\nE2B_HEREDOC_EOF____",+ ]++[email protected]_debug()+def test_from_dockerfile_copy_heredoc_keeps_docker_substitution_patterns():+ dockerfile = """FROM node:24+COPY <<EOF /etc/app.conf+${X/old/new} ${X//o/0} ${X/a\\/b/c} ${X/`/x} ${Y#\\*} ${Y%%\\}} ${Z:-foo\\}bar} ${Z:-a\\\\b}+EOF"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST=/etc/app.conf\n"+ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n'+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "${X/old/new} ${X//o/0} ${X/a\\/b/c} ${X/\\`/x} ${Y#\\*} ${Y%%\\}} ${Z:-foo\\}bar} ${Z:-a\\\\b}\nE2B_HEREDOC_EOF",+ ]++[email protected]_debug()+def test_from_dockerfile_copy_chmod_resolves_arg_and_env_values():+ dockerfile = """FROM node:24+ARG MODE=440+ENV FULL=0${MODE}+COPY --chmod=$MODE a /a+COPY --chmod=${FULL} b /b+COPY --chmod=${UNSET:-755} c /c"""++ template = Template().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["a", "/a", "", "0440"],+ ["b", "/b", "", "0440"],+ ["c", "/c", "", "0755"],+ ]++[email protected]_debug()+def test_from_dockerfile_copy_heredoc_with_shell_unsafe_name():+ dockerfile = """FROM node:24+COPY <<FOO;BAR /etc/+hi+FOO;BAR"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST='/etc/FOO;BAR'\n"+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_FOO_BAR >"$E2B_HEREDOC_DEST"\n'+ "hi\nE2B_HEREDOC_FOO_BAR",+ ]++[email protected]_debug()+def test_from_dockerfile_copy_heredoc_into_directory_expands_only_variables():+ dockerfile = """FROM node:24+COPY <<EOF /etc/+run `npm start` and $(id) for $USER, \\$(literal) and ${HOME:-$(x)}+EOF+COPY <<EOF .+x+EOF"""++ template = Template().from_dockerfile(dockerfile)+ runs = [+ i["args"][0]+ for i in _instructions(template)+ if i["type"] == InstructionType.RUN+ ]++ assert runs == [+ "E2B_HEREDOC_DEST=/etc/EOF\n"+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "run \\`npm start\\` and \\$(id) for $USER, \\$(literal) and ${HOME:-\\$(x)}\nE2B_HEREDOC_EOF",+ "E2B_HEREDOC_DEST=.\n"+ 'if [ -d "$E2B_HEREDOC_DEST" ]; then E2B_HEREDOC_DEST="$E2B_HEREDOC_DEST"/EOF; fi\n'+ 'mkdir -p "$(dirname "$E2B_HEREDOC_DEST")" && cat <<E2B_HEREDOC_EOF >"$E2B_HEREDOC_DEST"\n'+ "x\nE2B_HEREDOC_EOF",+ ]++[email protected]_debug()+def test_from_dockerfile_copy_with_literal_paths_and_zero_mode():+ dockerfile = """FROM node:24+COPY "<<EOF" /tmp/+COPY --chmod=000 secret.txt /tmp/"""++ template = Template().from_dockerfile(dockerfile)+ copies = [+ i["args"] for i in _instructions(template) if i["type"] == InstructionType.COPY+ ]++ assert copies == [+ ["<<EOF", "/tmp/", "", ""],+ ["secret.txt", "/tmp/", "", "0000"],+ ]++[email protected]_debug()+def test_from_dockerfile_combines_entrypoint_and_cmd():+ cases = [+ (+ 'ENTRYPOINT ["npm", "run"]\nCMD ["start", "--port 80"]',+ "npm run start '--port 80'",+ ),+ ('ENTRYPOINT ["npm"]\nCMD run start', "npm /bin/sh -c 'run start'"),+ ('ENTRYPOINT npm start\nCMD ["ignored"]', "npm start"),+ ("CMD npm start", "npm start"),+ ('CMD ["npm", "start"]', "npm start"),+ ("", None),+ ("CMD", None),+ ("ENTRYPOINT", None),+ ]+ for tail, expected in cases:+ template = Template().from_dockerfile(f"FROM node:24\n{tail}")+ assert template._template._start_cmd == expected, tail++[email protected]_debug()+def test_from_dockerfile_ignores_metadata_instructions_and_flags():+ dockerfile = """FROM --platform=linux/amd64 node:24+EXPOSE 80 443+VOLUME ["/data"]+LABEL maintainer="me"+STOPSIGNAL SIGTERM+HEALTHCHECK NONE+RUN --mount=type=cache,target=/root/.npm npm ci"""++ template = Template().from_dockerfile(dockerfile)+ instructions = _instructions(template)+ assert instructions[2]["type"] == InstructionType.RUN+ assert instructions[2]["args"] == ["npm ci"]++[email protected]_debug()+def test_from_dockerfile_rejects_invalid_dockerfiles():+ cases = [+ ("", "must contain a FROM"),+ ("RUN echo hi", "must contain a FROM"),+ ("FROM a\nFROM b", "Multi-stage"),+ ("FROM a\nRUN <<EOF\nnever closed", "unterminated heredoc"),+ ("FROM a\nCOPY <<EOF /x\n${}\nEOF", "bad substitution"),+ ("FROM a\nCOPY <<EOF /x\n${HOME:-\nEOF", "missing '}'"),+ ("FROM a\nCOPY <<EOF /x\n${X/a\nEOF", r"missing '/' in \$\{\}"),+ ("FROM a\nCOPY <<EOF /x\n${X:/a/b}\nEOF", r"unsupported modifier \(:/\)"),+ (+ "FROM a\nCOPY --chmod=$NOPE a b",+ r'invalid chmod value "\$NOPE" \(resolves to ""\)',+ ),+ ("FROM a\nBOGUS instruction", "unknown instruction: BOGUS"),+ ("FROM a\nCOPY --unknown=1 a b", "unknown flag: unknown"),+ ("FROM a\nCOPY --from=builder a b", "--from is not supported"),+ ("FROM a\nCOPY --toString=1 a b", "unknown flag: toString"),+ ('FROM a\nENV K="unterminated', "looking for matching double-quote"),+ ('FROM a\nRUN ["not", 1]', "Only strings are supported"),+ ]+ for dockerfile, expected in cases:+ with pytest.raises(DockerfileSyntaxError, match=expected):+ Template().from_dockerfile(dockerfile)diff --git a/packages/python-sdk/uv.lock b/packages/python-sdk/uv.lockindex 325002006..5679be50c 100644--- a/packages/python-sdk/uv.lock+++ b/packages/python-sdk/uv.lock@@ -169,15 +169,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/23/94/71338e2f0146ac10747a5537b3a1e45256e66b7c229869eb0ee787111b41/datamodel_code_generator-0.64.0-py3-none-any.whl", hash = "sha256:b7cd8bd41a312aa997aec6150670bad781847c5b674f17e4d70e78208a0fb990", size = 374698, upload-time = "2026-06-14T17:24:48.809Z" },]-[[package]]-name = "dockerfile-parse"-version = "2.0.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/92/df/929ee0b5d2c8bd8d713c45e71b94ab57c7e11e322130724d54f469b2cd48/dockerfile-parse-2.0.1.tar.gz", hash = "sha256:3184ccdc513221983e503ac00e1aa504a2aa8f84e5de673c46b0b6eee99ec7bc", size = 24556, upload-time = "2023-07-18T13:36:07.897Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/7a/6c/79cd5bc1b880d8c1a9a5550aa8dacd57353fa3bb2457227e1fb47383eb49/dockerfile_parse-2.0.1-py2.py3-none-any.whl", hash = "sha256:bdffd126d2eb26acf1066acb54cb2e336682e1d72b974a40894fac76a4df17f6", size = 14845, upload-time = "2023-07-18T13:36:06.052Z" },-]-[[package]]name = "e2b"version = "2.53.1"@@ -185,7 +176,7 @@ source = { editable = "." }dependencies = [{ name = "attrs" },{ name = "connectrpc" },- { name = "dockerfile-parse" },+ { name = "e2b-dockerfile-utils" },{ name = "h2" },{ name = "httpx" },{ name = "packaging" },@@ -220,7 +211,7 @@ dev = [requires-dist = [{ name = "attrs", specifier = ">=23.2.0" },{ name = "connectrpc", specifier = ">=0.11.1,<0.12" },- { name = "dockerfile-parse", specifier = ">=2.0.1,<3" },+ { name = "e2b-dockerfile-utils", editable = "../dockerfile-utils-python" },{ name = "h2", specifier = ">=4.4.1,<5" },{ name = "httpx", specifier = ">=0.27.0,<1.0.0" },{ name = "packaging", specifier = ">=24.1" },@@ -251,6 +242,20 @@ dev = [{ name = "ty", specifier = ">=0.0.15,<0.0.16" },]+[[package]]+name = "e2b-dockerfile-utils"+version = "0.0.0"+source = { editable = "../dockerfile-utils-python" }++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=9.0.3,<10" },+ { name = "ruff", specifier = ">=0.11.12,<0.12" },+ { name = "ty", specifier = ">=0.0.15,<0.0.16" },+]+[[package]]name = "e2b-openapi-python-client"version = "0.26.2"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1d53d01f1..7b10802b5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -243,6 +243,26 @@ importers:packages/desktop-python: {}+ packages/dockerfile-utils-js:+ devDependencies:+ '@types/node':+ specifier: 'catalog:'+ version: 20.19.43+ '@typescript/native':+ specifier: 'catalog:'+ version: [email protected]+ tsdown:+ specifier: 'catalog:'+ typescript:+ specifier: 'catalog:'+ version: '@typescript/[email protected]'+ vitest:+ specifier: 'catalog:'+ version: 4.1.11(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])(@typescript/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))++ packages/dockerfile-utils-python: {}+packages/js-sdk:dependencies:'@bufbuild/protobuf':@@ -254,15 +274,15 @@ importers:'@connectrpc/connect-web':specifier: ^2.2.0version: 2.2.0(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))+ '@e2b/dockerfile-utils':+ specifier: workspace:^+ version: link:../dockerfile-utils-jschalk:specifier: ^5.6.2version: 5.6.2compare-versions:specifier: ^6.1.1version: 6.1.1- dockerfile-ast:- specifier: ^0.7.1- version: 0.7.1glob:specifier: ^13.0.6version: 13.0.6@@ -341,7 +361,11 @@ importers:specifier: npm:[email protected]version: [email protected]- packages/python-sdk: {}+ packages/python-sdk:+ dependencies:+ '@e2b/dockerfile-utils-python':+ specifier: workspace:*+ version: link:../dockerfile-utils-pythonpackages:@@ -2807,9 +2831,6 @@ packages:resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}engines: {node: '>=8'}- resolution: {integrity: sha512-oX/A4I0EhSkGqrFv0YuvPkBUSYp1XiY8O8zAKc8Djglx8ocz+JfOr8gP0ryRMC2myqvDLagmnZaU9ot1vG2ijw==}-resolution: {integrity: sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==}engines: {node: '>=12'}@@ -3513,10 +3534,6 @@ packages:resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==}engines: {node: '>= 0.4'}- resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==}- engines: {node: '>=12.20.0'}-resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==}engines: {node: '>=12.20.0'}@@ -3639,10 +3656,6 @@ packages:resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}engines: {node: '>=8.6'}- resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}- engines: {node: '>=12'}-resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}engines: {node: '>=12'}@@ -3955,9 +3968,6 @@ packages:resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}engines: {node: '>= 0.8'}- resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}-resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}@@ -4312,12 +4322,6 @@ packages:jsdom:optional: true- resolution: {integrity: sha512-Gsfr9S8LU3S6885cS+NaleasJ0n3V5y/SOTqHCifQiXWFw3G9w9/YItDfwHrlCz+dSZWWZ8ilYVMcJe7Sz7Sxw==}-- resolution: {integrity: sha512-nQsacoiijvl0fRf2q28uFDrAVwRhdCa3QveiF7/CX0r18mLR5FU/1WskSsCKOjmEbtteKUnY8x8Yzxop+k0zwg==}-resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==}engines: {node: 20 || >=22}@@ -5988,7 +5992,7 @@ snapshots:'@vitest/spy': 4.1.11'@vitest/utils': 4.1.11chai: 6.2.2- tinyrainbow: 3.1.0+ tinyrainbow: 3.2.0'@vitest/[email protected]([email protected](@types/[email protected])(@typescript/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:@@ -6001,7 +6005,7 @@ snapshots:'@vitest/[email protected]':dependencies:- tinyrainbow: 3.1.0+ tinyrainbow: 3.2.0'@vitest/[email protected]':dependencies:@@ -6367,11 +6371,6 @@ snapshots:dependencies:path-type: 4.0.0- dependencies:- vscode-languageserver-textdocument: 1.0.15- vscode-languageserver-types: 3.18.4-@@ -6627,10 +6626,6 @@ snapshots:dependencies:walk-up-path: 4.0.0- optionalDependencies:- picomatch: 4.0.5-optionalDependencies:picomatch: 4.0.7@@ -7247,8 +7242,6 @@ snapshots:has-symbols: 1.1.0object-keys: 1.1.1- [email protected]: {}-@@ -7388,8 +7381,6 @@ snapshots:- [email protected]: {}-@@ -7488,7 +7479,7 @@ snapshots:dependencies:dts-resolver: 3.0.0([email protected])get-tsconfig: 5.0.0-beta.5- obug: 2.1.4+ obug: 2.2.1rolldown: 1.2.5yuku-ast: 0.8.7yuku-codegen: 0.8.7@@ -7778,8 +7769,6 @@ snapshots:- [email protected]: {}-@@ -7892,8 +7881,8 @@ snapshots:dependencies:- fdir: 6.5.0([email protected])- picomatch: 4.0.5+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7@@ -7927,8 +7916,8 @@ snapshots:empathic: 2.0.1hookable: 6.1.1import-without-cache: 0.4.0- obug: 2.1.4- picomatch: 4.0.5+ obug: 2.2.1+ picomatch: 4.0.7rolldown: 1.2.5tinyexec: 1.2.4@@ -8095,14 +8084,14 @@ snapshots:es-module-lexer: 2.1.0expect-type: 1.3.0magic-string: 0.30.21- obug: 2.1.4+ obug: 2.2.1pathe: 2.0.3- picomatch: 4.0.5- std-env: 4.1.0+ picomatch: 4.0.7+ std-env: 4.3.0tinybench: 2.9.0tinyexec: 1.2.4tinyglobby: 0.2.17- tinyrainbow: 3.1.0+ tinyrainbow: 3.2.0vite: 6.4.3(@types/[email protected])([email protected])([email protected])([email protected])([email protected])why-is-node-running: 2.3.0optionalDependencies:@@ -8112,10 +8101,6 @@ snapshots:transitivePeerDependencies:- msw- [email protected]: {}-- [email protected]: {}-