From ce4ec23b78461f5b5c1f96cbf192f1e9d45ee635 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Tue, 10 Nov 2026 17:30:25 -0500 Subject: [PATCH 1/8] feat: add Dockerfile parser Co-Authored-By: Claude Fable 5.2 --- README.md | 17 ++ docs/syntax-tree.md | 342 ++++++++++++++++++++++++++++ src/index.ts | 3 + src/parser/parse.spec.ts | 467 +++++++++++++++++++++++++++++++++++++++ src/parser/parse.ts | 417 ++++++++++++++++++++++++++++++++++ src/types.ts | 328 +++++++++++++++++++++++++++ 6 files changed, 1574 insertions(+) create mode 100644 docs/syntax-tree.md create mode 100644 src/parser/parse.spec.ts create mode 100644 src/parser/parse.ts create mode 100644 src/types.ts diff --git a/README.md b/README.md index f886573..204735c 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,23 @@ npm install --save-dev eslint @eslint/docker Requires Node.js `^20.19.0 || ^22.13.0 || >=24`. Tested with ESLint v10. +## Syntax tree + +The tree format is documented in [docs/syntax-tree.md](docs/syntax-tree.md). +Nodes carry `start`/`end` character offsets instead of `range`/`loc` +properties; use `sourceCode.getRange(node)` and `sourceCode.getLoc(node)`. + +The parser is also exported directly: + +```js +import { parseDocker } from "@eslint/docker"; + +const { ast, comments } = parseDocker("FROM node:20-alpine\n"); +``` + +Parsing never fails: the underlying parser is error-tolerant, so malformed +input still produces a tree. + ## Development ```bash diff --git a/docs/syntax-tree.md b/docs/syntax-tree.md new file mode 100644 index 0000000..235b289 --- /dev/null +++ b/docs/syntax-tree.md @@ -0,0 +1,342 @@ +# Dockerfile Syntax Tree Format + +`@eslint/docker` parses Dockerfile source code into an ESTree-style syntax +tree by wrapping the +[dockerfile-ast](https://www.npmjs.com/package/dockerfile-ast) parser (the +parser behind Docker's official language server) and translating its +output. + +## Positions + +Every node has three common properties: + +```ts +interface DockerNodeBase { + type: string; + start: number; // 0-based character offset, inclusive + end: number; // 0-based character offset, exclusive +} +``` + +Nodes intentionally do **not** carry `range` or `loc` properties. To get +position information, use the `SourceCode` methods: + +```js +const range = sourceCode.getRange(node); // [start, end] +const loc = sourceCode.getLoc(node); // { start: { line, column }, end: ... } +``` + +Lines and columns are 1-based. + +An instruction that uses line continuations (`\`) spans all of its +physical lines. Its argument tokens have the continuations resolved: each +token is a single whitespace-delimited word with offsets pointing at the +physical line it appears on. + +## Dockerfile + +The root node. `comments` contains every comment in the file in source +order, and `directives` contains parser directives such as +`# syntax=docker/dockerfile:1`; neither is part of the traversed tree. + +```ts +interface Dockerfile extends DockerNodeBase { + type: "Dockerfile"; + body: Instruction[]; + comments: Comment[]; + directives: ParserDirective[]; +} + +interface Comment extends DockerNodeBase { + type: "Comment"; + text: string; // text after `#`, trimmed +} + +interface ParserDirective extends DockerNodeBase { + type: "ParserDirective"; + name: string; // e.g. "syntax", "escape" + value: string; +} +``` + +Dockerfile comments must begin at the start of a line; a `#` after an +instruction is part of its arguments. + +## Instructions + +Every instruction node carries its canonical uppercase `keyword`. The +keyword as written (which may be lowercase) occupies +`[start, start + keyword.length)` in the source text. + +```ts +interface InstructionBase extends DockerNodeBase { + keyword: string; // always uppercase: "FROM", "RUN", ... +} +``` + +### Shared pieces + +```ts +interface Argument extends DockerNodeBase { + type: "Argument"; + value: string; +} + +interface Flag extends DockerNodeBase { + type: "Flag"; + name: string; // without the `--` prefix + value: string | null; // null when written without `=` +} + +interface KeyValuePair extends DockerNodeBase { + type: "KeyValuePair"; + key: Argument; + value: Argument | null; +} + +interface ShellForm extends DockerNodeBase { + type: "ShellForm"; + arguments: Argument[]; // whitespace-delimited tokens +} + +interface ExecForm extends DockerNodeBase { + type: "ExecForm"; + elements: Argument[]; // JSON array elements +} +``` + +`Argument` is used in several positions with slightly different value +semantics: + +- **Shell-form tokens** (`RUN echo hi`): `value` is the token exactly as + written, including any quotes. Tokens are split on whitespace only, so + `echo "a b"` produces the tokens `echo`, `"a`, and `b"`. +- **Exec-form elements** (`CMD ["a b"]`): `value` is the raw text between + the double quotes (`a b`), while the offsets include the quotes. +- **Key/value pairs** (`ENV a="b c"`): the pair's `value` argument has + quotes removed from its string, while the offsets include them. + +```dockerfile +FROM node:20 +RUN echo hello && echo world +``` + +### FROM + +```ts +interface FromInstruction extends InstructionBase { + type: "FromInstruction"; + keyword: "FROM"; + flags: Flag[]; // e.g. --platform=linux/amd64 + image: ImageReference | null; + alias: StageName | null; // the name after AS +} + +interface ImageReference extends DockerNodeBase { + type: "ImageReference"; + name: string; // "node", "ghcr.io/org/app", or a stage name + tag: string | null; // "20-alpine" in node:20-alpine + digest: string | null; // "sha256:..." in node@sha256:... +} + +interface StageName extends DockerNodeBase { + type: "StageName"; + name: string; +} +``` + +A `FROM` that references an earlier build stage still produces an +`ImageReference`; its `name` is the stage name. + +### RUN, CMD, ENTRYPOINT, and SHELL + +```ts +interface RunInstruction extends InstructionBase { + type: "RunInstruction"; + keyword: "RUN"; + flags: Flag[]; // e.g. --mount=type=cache + command: ShellForm | ExecForm | null; +} + +interface CmdInstruction extends InstructionBase { + type: "CmdInstruction"; + keyword: "CMD"; + command: ShellForm | ExecForm | null; +} + +interface EntrypointInstruction extends InstructionBase { + type: "EntrypointInstruction"; + keyword: "ENTRYPOINT"; + command: ShellForm | ExecForm | null; +} + +interface ShellInstruction extends InstructionBase { + type: "ShellInstruction"; + keyword: "SHELL"; + command: ExecForm | null; // SHELL only accepts the JSON form +} +``` + +### COPY and ADD + +Both forms (`COPY a b /dest` and `COPY ["a", "b", "/dest"]`) produce the +same shape: the last argument is the destination and the rest are sources. + +```ts +interface CopyInstruction extends InstructionBase { + type: "CopyInstruction"; + keyword: "COPY"; + flags: Flag[]; // e.g. --from=build, --chown=node:node + sources: Argument[]; + destination: Argument | null; +} + +interface AddInstruction extends InstructionBase { + type: "AddInstruction"; + keyword: "ADD"; + flags: Flag[]; // e.g. --checksum=sha256:... + sources: Argument[]; + destination: Argument | null; +} +``` + +### ENV, ARG, and LABEL + +All three produce `pairs` of key/value nodes. The legacy space-separated +form `ENV key value` produces one pair whose value spans the rest of the +instruction. A valueless `ARG NAME` has `value: null`. + +```ts +interface EnvInstruction extends InstructionBase { + type: "EnvInstruction"; + keyword: "ENV"; + pairs: KeyValuePair[]; +} + +interface ArgInstruction extends InstructionBase { + type: "ArgInstruction"; + keyword: "ARG"; + pairs: KeyValuePair[]; +} + +interface LabelInstruction extends InstructionBase { + type: "LabelInstruction"; + keyword: "LABEL"; + pairs: KeyValuePair[]; +} +``` + +### Single-argument instructions + +```ts +interface WorkdirInstruction extends InstructionBase { + type: "WorkdirInstruction"; + keyword: "WORKDIR"; + path: Argument | null; +} + +interface UserInstruction extends InstructionBase { + type: "UserInstruction"; + keyword: "USER"; + user: Argument | null; +} + +interface StopsignalInstruction extends InstructionBase { + type: "StopsignalInstruction"; + keyword: "STOPSIGNAL"; + signal: Argument | null; +} +``` + +### EXPOSE and VOLUME + +```ts +interface ExposeInstruction extends InstructionBase { + type: "ExposeInstruction"; + keyword: "EXPOSE"; + ports: Argument[]; // e.g. "8080", "9090/udp" +} + +interface VolumeInstruction extends InstructionBase { + type: "VolumeInstruction"; + keyword: "VOLUME"; + paths: Argument[]; // from either the plain or the JSON form +} +``` + +### HEALTHCHECK + +```ts +interface HealthcheckInstruction extends InstructionBase { + type: "HealthcheckInstruction"; + keyword: "HEALTHCHECK"; + flags: Flag[]; // e.g. --interval=30s + subcommand: Argument | null; // "CMD" or "NONE" + arguments: Argument[]; // tokens after the subcommand +} +``` + +### ONBUILD + +The trigger is a full nested instruction node starting at its own keyword, +so rules that visit instruction types also see ONBUILD triggers. + +```ts +interface OnbuildInstruction extends InstructionBase { + type: "OnbuildInstruction"; + keyword: "ONBUILD"; + trigger: Instruction | null; +} +``` + +### MAINTAINER and unknown instructions + +```ts +interface MaintainerInstruction extends InstructionBase { + type: "MaintainerInstruction"; + keyword: "MAINTAINER"; + arguments: Argument[]; +} + +interface GenericInstruction extends InstructionBase { + type: "GenericInstruction"; + keyword: string; // uppercased unknown keyword + arguments: Argument[]; +} +``` + +## Traversal order + +Rules receive nodes in this traversal order (see +`src/visitor-keys.ts`): + +| Node type | Visited children | +| ------------------------ | ---------------------------------- | +| `Dockerfile` | `body` | +| `FromInstruction` | `flags`, `image`, `alias` | +| `RunInstruction` | `flags`, `command` | +| `CmdInstruction` | `command` | +| `EntrypointInstruction` | `command` | +| `ShellInstruction` | `command` | +| `CopyInstruction` | `flags`, `sources`, `destination` | +| `AddInstruction` | `flags`, `sources`, `destination` | +| `EnvInstruction` | `pairs` | +| `ArgInstruction` | `pairs` | +| `LabelInstruction` | `pairs` | +| `WorkdirInstruction` | `path` | +| `UserInstruction` | `user` | +| `ExposeInstruction` | `ports` | +| `VolumeInstruction` | `paths` | +| `StopsignalInstruction` | `signal` | +| `HealthcheckInstruction` | `flags`, `subcommand`, `arguments` | +| `OnbuildInstruction` | `trigger` | +| `MaintainerInstruction` | `arguments` | +| `GenericInstruction` | `arguments` | +| `KeyValuePair` | `key`, `value` | +| `ShellForm` | `arguments` | +| `ExecForm` | `elements` | + +`Comment`, `ParserDirective`, `Argument`, `Flag`, `ImageReference`, and +`StageName` are leaves. Comments and parser directives are not part of the +traversed tree; access them via `sourceCode.ast.comments` and +`sourceCode.ast.directives`. diff --git a/src/index.ts b/src/index.ts index a5ff205..46d5ae2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,3 +22,6 @@ const plugin = { //------------------------------------------------------------------------------ export default plugin; +export { parseDocker } from "./parser/parse.js"; +export { INSTRUCTION_TYPES } from "./types.js"; +export type * from "./types.js"; diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts new file mode 100644 index 0000000..f72e9ed --- /dev/null +++ b/src/parser/parse.spec.ts @@ -0,0 +1,467 @@ +/** + * @fileoverview Unit tests for the Dockerfile parser wrapper. + * @author Claude Fable 5 + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import { describe, expect, it } from "vitest"; +import { parseDocker } from "./parse.js"; +import type { + AddInstructionNode, + ArgInstructionNode, + CmdInstructionNode, + CopyInstructionNode, + EntrypointInstructionNode, + EnvInstructionNode, + ExecFormNode, + ExposeInstructionNode, + FromInstructionNode, + GenericInstructionNode, + HealthcheckInstructionNode, + LabelInstructionNode, + MaintainerInstructionNode, + OnbuildInstructionNode, + RunInstructionNode, + ShellFormNode, + ShellInstructionNode, + StopsignalInstructionNode, + UserInstructionNode, + VolumeInstructionNode, + WorkdirInstructionNode, +} from "../types.js"; + +describe("parseDocker", () => { + it("should produce an empty Dockerfile node for empty input", () => { + const { ast, comments } = parseDocker(""); + + expect(ast).toEqual({ + type: "Dockerfile", + body: [], + comments: [], + directives: [], + start: 0, + end: 0, + }); + expect(comments).toEqual([]); + }); + + it("should span the whole text with the root node", () => { + const text = "FROM node:20\n"; + const { ast } = parseDocker(text); + + expect(ast.start).toBe(0); + expect(ast.end).toBe(text.length); + }); + + describe("comments and directives", () => { + it("should collect comments with offsets and stripped text", () => { + const text = "# hello world\nFROM node:20\n"; + const { ast, comments } = parseDocker(text); + + expect(comments).toHaveLength(1); + expect(comments[0]).toMatchObject({ + type: "Comment", + text: "hello world", + start: 0, + end: 13, + }); + expect(ast.comments).toBe(comments); + }); + + it("should treat leading pragmas as parser directives", () => { + const text = "# syntax=docker/dockerfile:1\nFROM node:20\n"; + const { ast } = parseDocker(text); + + expect(ast.directives).toHaveLength(1); + expect(ast.directives[0]).toMatchObject({ + type: "ParserDirective", + name: "syntax", + value: "docker/dockerfile:1", + start: 0, + end: 28, + }); + }); + }); + + describe("FROM", () => { + it("should parse image name, tag, and stage alias", () => { + const text = "FROM node:20-alpine AS base\n"; + const { ast } = parseDocker(text); + const from = ast.body[0] as FromInstructionNode; + + expect(from.type).toBe("FromInstruction"); + expect(from.keyword).toBe("FROM"); + expect(from.start).toBe(0); + expect(from.end).toBe(27); + expect(from.image).toMatchObject({ + type: "ImageReference", + name: "node", + tag: "20-alpine", + digest: null, + start: 5, + end: 19, + }); + expect(from.alias).toMatchObject({ + type: "StageName", + name: "base", + start: 23, + end: 27, + }); + }); + + it("should parse digests and platform flags", () => { + const text = + "FROM --platform=linux/amd64 alpine@sha256:abc123def\n"; + const { ast } = parseDocker(text); + const from = ast.body[0] as FromInstructionNode; + + expect(from.image).toMatchObject({ + name: "alpine", + tag: null, + digest: "sha256:abc123def", + }); + expect(from.flags).toHaveLength(1); + expect(from.flags[0]).toMatchObject({ + type: "Flag", + name: "platform", + value: "linux/amd64", + }); + expect(from.alias).toBeNull(); + }); + + it("should handle FROM without an image", () => { + const { ast } = parseDocker("FROM\n"); + const from = ast.body[0] as FromInstructionNode; + + expect(from.image).toBeNull(); + }); + }); + + describe("RUN", () => { + it("should parse shell form commands into tokens", () => { + const text = "RUN apt-get update && apt-get install -y git\n"; + const { ast } = parseDocker(text); + const run = ast.body[0] as RunInstructionNode; + const command = run.command as ShellFormNode; + + expect(run.type).toBe("RunInstruction"); + expect(command.type).toBe("ShellForm"); + expect(command.arguments.map(argument => argument.value)).toEqual([ + "apt-get", + "update", + "&&", + "apt-get", + "install", + "-y", + "git", + ]); + expect(command.start).toBe(4); + expect(command.end).toBe(44); + }); + + it("should resolve line continuations in shell form commands", () => { + const text = + "RUN apt-get update && \\\n apt-get install -y git\n"; + const { ast } = parseDocker(text); + const run = ast.body[0] as RunInstructionNode; + const command = run.command as ShellFormNode; + + expect(command.arguments.map(argument => argument.value)).toEqual([ + "apt-get", + "update", + "&&", + "apt-get", + "install", + "-y", + "git", + ]); + + // The instruction spans both physical lines. + expect(run.start).toBe(0); + expect(run.end).toBe(text.length - 1); + }); + + it("should parse exec form commands into elements", () => { + const text = 'RUN ["/bin/bash", "-c", "echo hi"]\n'; + const { ast } = parseDocker(text); + const run = ast.body[0] as RunInstructionNode; + const command = run.command as ExecFormNode; + + expect(command.type).toBe("ExecForm"); + expect(command.elements.map(element => element.value)).toEqual([ + "/bin/bash", + "-c", + "echo hi", + ]); + + // The form spans the brackets; elements include their quotes. + expect(command.start).toBe(4); + expect(command.end).toBe(34); + expect(command.elements[0]).toMatchObject({ start: 5, end: 16 }); + }); + + it("should have a null command for empty RUN", () => { + const { ast } = parseDocker("RUN\n"); + const run = ast.body[0] as RunInstructionNode; + + expect(run.command).toBeNull(); + }); + }); + + describe("CMD, ENTRYPOINT, and SHELL", () => { + it("should parse CMD and ENTRYPOINT like RUN", () => { + const text = 'CMD npm start\nENTRYPOINT ["node", "app.js"]\n'; + const { ast } = parseDocker(text); + const cmd = ast.body[0] as CmdInstructionNode; + const entrypoint = ast.body[1] as EntrypointInstructionNode; + + expect(cmd.type).toBe("CmdInstruction"); + expect(cmd.command?.type).toBe("ShellForm"); + expect(entrypoint.type).toBe("EntrypointInstruction"); + expect(entrypoint.command?.type).toBe("ExecForm"); + }); + + it("should only accept exec form for SHELL", () => { + const text = 'SHELL ["powershell", "-Command"]\nSHELL bogus\n'; + const { ast } = parseDocker(text); + const good = ast.body[0] as ShellInstructionNode; + const bad = ast.body[1] as ShellInstructionNode; + + expect(good.command?.type).toBe("ExecForm"); + expect( + good.command?.elements.map(element => element.value), + ).toEqual(["powershell", "-Command"]); + expect(bad.command).toBeNull(); + }); + }); + + describe("COPY and ADD", () => { + it("should split sources and destination", () => { + const text = "COPY --chown=node:node src/ lib/ /app/\n"; + const { ast } = parseDocker(text); + const copy = ast.body[0] as CopyInstructionNode; + + expect(copy.type).toBe("CopyInstruction"); + expect(copy.sources.map(source => source.value)).toEqual([ + "src/", + "lib/", + ]); + expect(copy.destination?.value).toBe("/app/"); + expect(copy.flags[0]).toMatchObject({ + name: "chown", + value: "node:node", + }); + }); + + it("should support the JSON form", () => { + const text = 'ADD ["src dir", "/app/"]\n'; + const { ast } = parseDocker(text); + const add = ast.body[0] as AddInstructionNode; + + expect(add.type).toBe("AddInstruction"); + expect(add.sources.map(source => source.value)).toEqual([ + "src dir", + ]); + expect(add.destination?.value).toBe("/app/"); + }); + + it("should handle a missing destination", () => { + const { ast } = parseDocker("COPY src/\n"); + const copy = ast.body[0] as CopyInstructionNode; + + expect(copy.sources).toEqual([]); + expect(copy.destination?.value).toBe("src/"); + }); + }); + + describe("ENV, LABEL, and ARG", () => { + it("should parse = pairs with quoted values", () => { + const text = 'ENV FOO=bar BAZ="qux quux"\n'; + const { ast } = parseDocker(text); + const env = ast.body[0] as EnvInstructionNode; + + expect(env.type).toBe("EnvInstruction"); + expect(env.pairs).toHaveLength(2); + expect(env.pairs[0]).toMatchObject({ type: "KeyValuePair" }); + expect(env.pairs[0]?.key).toMatchObject({ + value: "FOO", + start: 4, + end: 7, + }); + expect(env.pairs[0]?.value).toMatchObject({ value: "bar" }); + + // The value string is unquoted, but the offsets include quotes. + expect(env.pairs[1]?.value).toMatchObject({ + value: "qux quux", + start: 16, + end: 26, + }); + }); + + it("should parse the legacy space-separated ENV form", () => { + const { ast } = parseDocker("ENV OLD style value\n"); + const env = ast.body[0] as EnvInstructionNode; + + expect(env.pairs).toHaveLength(1); + expect(env.pairs[0]?.key.value).toBe("OLD"); + expect(env.pairs[0]?.value?.value).toBe("style value"); + }); + + it("should parse valueless ARG declarations", () => { + const { ast } = parseDocker("ARG VERSION\nARG DEBUG=false\n"); + const bare = ast.body[0] as ArgInstructionNode; + const withDefault = ast.body[1] as ArgInstructionNode; + + expect(bare.type).toBe("ArgInstruction"); + expect(bare.pairs[0]?.key.value).toBe("VERSION"); + expect(bare.pairs[0]?.value).toBeNull(); + expect(withDefault.pairs[0]?.value?.value).toBe("false"); + }); + + it("should parse LABEL pairs", () => { + const { ast } = parseDocker('LABEL maintainer="me@example.com"\n'); + const label = ast.body[0] as LabelInstructionNode; + + expect(label.type).toBe("LabelInstruction"); + expect(label.pairs[0]?.key.value).toBe("maintainer"); + expect(label.pairs[0]?.value?.value).toBe("me@example.com"); + }); + }); + + describe("single-argument instructions", () => { + it("should parse WORKDIR, USER, and STOPSIGNAL", () => { + const text = "WORKDIR /app\nUSER node\nSTOPSIGNAL SIGTERM\n"; + const { ast } = parseDocker(text); + const workdir = ast.body[0] as WorkdirInstructionNode; + const user = ast.body[1] as UserInstructionNode; + const stopsignal = ast.body[2] as StopsignalInstructionNode; + + expect(workdir.type).toBe("WorkdirInstruction"); + expect(workdir.path?.value).toBe("/app"); + expect(user.type).toBe("UserInstruction"); + expect(user.user?.value).toBe("node"); + expect(stopsignal.type).toBe("StopsignalInstruction"); + expect(stopsignal.signal?.value).toBe("SIGTERM"); + }); + + it("should handle missing arguments", () => { + const { ast } = parseDocker("WORKDIR\nUSER\n"); + + expect((ast.body[0] as WorkdirInstructionNode).path).toBeNull(); + expect((ast.body[1] as UserInstructionNode).user).toBeNull(); + }); + }); + + describe("EXPOSE and VOLUME", () => { + it("should parse EXPOSE ports", () => { + const { ast } = parseDocker("EXPOSE 8080 9090/udp\n"); + const expose = ast.body[0] as ExposeInstructionNode; + + expect(expose.type).toBe("ExposeInstruction"); + expect(expose.ports.map(port => port.value)).toEqual([ + "8080", + "9090/udp", + ]); + }); + + it("should parse VOLUME in both forms", () => { + const text = 'VOLUME /data /logs\nVOLUME ["/var/db"]\n'; + const { ast } = parseDocker(text); + const plain = ast.body[0] as VolumeInstructionNode; + const json = ast.body[1] as VolumeInstructionNode; + + expect(plain.paths.map(path => path.value)).toEqual([ + "/data", + "/logs", + ]); + expect(json.paths.map(path => path.value)).toEqual(["/var/db"]); + }); + }); + + describe("HEALTHCHECK", () => { + it("should parse the subcommand, flags, and command tokens", () => { + const text = + "HEALTHCHECK --interval=5s CMD curl -f http://localhost/\n"; + const { ast } = parseDocker(text); + const healthcheck = ast.body[0] as HealthcheckInstructionNode; + + expect(healthcheck.type).toBe("HealthcheckInstruction"); + expect(healthcheck.subcommand?.value).toBe("CMD"); + expect(healthcheck.flags[0]).toMatchObject({ + name: "interval", + value: "5s", + }); + expect( + healthcheck.arguments.map(argument => argument.value), + ).toEqual(["curl", "-f", "http://localhost/"]); + }); + + it("should parse HEALTHCHECK NONE", () => { + const { ast } = parseDocker("HEALTHCHECK NONE\n"); + const healthcheck = ast.body[0] as HealthcheckInstructionNode; + + expect(healthcheck.subcommand?.value).toBe("NONE"); + expect(healthcheck.arguments).toEqual([]); + }); + }); + + describe("ONBUILD", () => { + it("should parse the trigger as a nested instruction", () => { + const text = "ONBUILD COPY . /app\n"; + const { ast } = parseDocker(text); + const onbuild = ast.body[0] as OnbuildInstructionNode; + const trigger = onbuild.trigger as CopyInstructionNode; + + expect(onbuild.type).toBe("OnbuildInstruction"); + expect(trigger.type).toBe("CopyInstruction"); + expect(trigger.keyword).toBe("COPY"); + + // The trigger starts at its own keyword. + expect(trigger.start).toBe(8); + expect(trigger.destination?.value).toBe("/app"); + }); + + it("should handle a missing trigger", () => { + const { ast } = parseDocker("ONBUILD\n"); + const onbuild = ast.body[0] as OnbuildInstructionNode; + + expect(onbuild.trigger).toBeNull(); + }); + }); + + describe("other instructions", () => { + it("should parse MAINTAINER arguments", () => { + const { ast } = parseDocker( + "MAINTAINER Jane Doe \n", + ); + const maintainer = ast.body[0] as MaintainerInstructionNode; + + expect(maintainer.type).toBe("MaintainerInstruction"); + expect( + maintainer.arguments.map(argument => argument.value), + ).toEqual(["Jane", "Doe", ""]); + }); + + it("should fall back to GenericInstruction for unknown keywords", () => { + const { ast } = parseDocker("BOGUS one two\n"); + const generic = ast.body[0] as GenericInstructionNode; + + expect(generic.type).toBe("GenericInstruction"); + expect(generic.keyword).toBe("BOGUS"); + expect(generic.arguments.map(argument => argument.value)).toEqual([ + "one", + "two", + ]); + }); + + it("should canonicalize lowercase keywords", () => { + const { ast } = parseDocker("from node:20\nrun echo hi\n"); + + expect(ast.body[0]?.keyword).toBe("FROM"); + expect(ast.body[1]?.keyword).toBe("RUN"); + }); + }); +}); diff --git a/src/parser/parse.ts b/src/parser/parse.ts new file mode 100644 index 0000000..f84cba4 --- /dev/null +++ b/src/parser/parse.ts @@ -0,0 +1,417 @@ +/** + * @fileoverview Parses Dockerfile source code into an ESTree-style syntax + * tree by wrapping the dockerfile-ast parser (the parser behind Docker's + * official language server) and translating its tree. See + * docs/syntax-tree.md for the tree format. + * @author Claude Fable 5 + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import { + DockerfileParser, + From, + Healthcheck, + Instruction, + JSONInstruction, + ModifiableInstruction, + Onbuild, + PropertyInstruction, +} from "dockerfile-ast"; +import type { + ArgumentNode, + CommandBodyNode, + CommentNode, + DockerfileNode, + ExecFormNode, + FlagNode, + InstructionNode, + KeyValuePairNode, + ParserDirectiveNode, + ShellFormNode, +} from "../types.js"; + +/** An LSP-style position as reported by dockerfile-ast. */ +interface Position { + line: number; + character: number; +} + +/** An LSP-style range as reported by dockerfile-ast. */ +interface Range { + start: Position; + end: Position; +} + +export interface DockerParseResult { + ast: DockerfileNode; + comments: CommentNode[]; +} + +/** + * Creates a converter from LSP line/character positions to character + * offsets in the source text. + */ +function createPositionConverter( + text: string, +): (position: Range["start"]) => number { + const lineStarts = [0]; + + for (let i = 0; i < text.length; i++) { + if (text[i] === "\n") { + lineStarts.push(i + 1); + } + } + + return position => { + const lineStart = lineStarts[ + Math.min(position.line, lineStarts.length - 1) + ] as number; + + return Math.min(lineStart + position.character, text.length); + }; +} + +/** + * Parses Dockerfile source code into an ESTree-style syntax tree. The + * underlying parser is error-tolerant, so parsing never throws: malformed + * input still produces a tree. + */ +export function parseDocker(text: string): DockerParseResult { + const dockerfile = DockerfileParser.parse(text); + const offsetAt = createPositionConverter(text); + + const spanOf = (range: Range): { start: number; end: number } => ({ + start: offsetAt(range.start), + end: offsetAt(range.end), + }); + + function argumentNode(value: string, range: Range): ArgumentNode { + return { type: "Argument", value, ...spanOf(range) }; + } + + function convertFlags(instruction: ModifiableInstruction): FlagNode[] { + return instruction.getFlags().map(flag => ({ + type: "Flag" as const, + name: flag.getName(), + value: flag.getValue(), + ...spanOf(flag.getRange()), + })); + } + + function convertArguments(instruction: Instruction): ArgumentNode[] { + return instruction + .getArguments() + .map(argument => + argumentNode(argument.getValue(), argument.getRange()), + ); + } + + /** + * Converts the string elements of a JSON (exec form) array. The + * upstream parser collapses whitespace in its argument values, so the + * value is sliced out of the source text instead: it is the raw text + * between the quotes. Offsets include the quotes. + */ + function convertJsonStrings(instruction: JSONInstruction): ArgumentNode[] { + return instruction.getJSONStrings().map(jsonString => { + const inner = spanOf(jsonString.getJSONRange()); + + return { + type: "Argument" as const, + value: text.slice(inner.start, inner.end), + ...spanOf(jsonString.getRange()), + }; + }); + } + + /** + * Converts the JSON array of an exec-form instruction. The node spans + * from the opening to the closing bracket. + */ + function convertExecForm(instruction: JSONInstruction): ExecFormNode { + const elements = convertJsonStrings(instruction); + const openingBracket = instruction.getOpeningBracket(); + const closingBracket = instruction.getClosingBracket(); + const first = openingBracket + ? spanOf(openingBracket.getRange()) + : (elements[0] as ArgumentNode); + const last = closingBracket + ? spanOf(closingBracket.getRange()) + : (elements.at(-1) ?? first); + + return { + type: "ExecForm", + elements, + start: first.start, + end: last.end, + }; + } + + /** + * Converts the arguments of a shell-form instruction. The node spans + * from the first to the last token. + */ + function convertShellForm(args: ArgumentNode[]): ShellFormNode { + return { + type: "ShellForm", + arguments: args, + start: (args[0] as ArgumentNode).start, + end: (args.at(-1) as ArgumentNode).end, + }; + } + + function convertCommandBody( + instruction: JSONInstruction, + ): CommandBodyNode | null { + if (instruction.getOpeningBracket()) { + return convertExecForm(instruction); + } + + const args = convertArguments(instruction); + + return args.length > 0 ? convertShellForm(args) : null; + } + + function convertPairs( + instruction: PropertyInstruction, + ): KeyValuePairNode[] { + return instruction.getProperties().map(property => { + const valueRange = property.getValueRange(); + const value = property.getValue(); + + return { + type: "KeyValuePair" as const, + key: argumentNode(property.getName(), property.getNameRange()), + value: + valueRange && value !== null + ? argumentNode(value, valueRange) + : null, + ...spanOf(property.getRange()), + }; + }); + } + + function convertInstruction(instruction: Instruction): InstructionNode { + const keyword = instruction.getKeyword(); + const span = spanOf(instruction.getRange()); + + if (instruction instanceof From) { + const imageRange = instruction.getImageRange(); + const stageName = instruction.getBuildStage(); + const stageRange = instruction.getBuildStageRange(); + + return { + type: "FromInstruction", + keyword: "FROM", + flags: convertFlags(instruction), + image: imageRange + ? { + type: "ImageReference", + name: instruction.getImageName() ?? "", + tag: instruction.getImageTag(), + digest: instruction.getImageDigest(), + ...spanOf(imageRange), + } + : null, + alias: + stageName !== null && stageRange + ? { + type: "StageName", + name: stageName, + ...spanOf(stageRange), + } + : null, + ...span, + }; + } + + if (instruction instanceof Healthcheck) { + const subcommand = instruction.getSubcommand(); + const args = convertArguments(instruction); + const subcommandNode = subcommand + ? argumentNode(subcommand.getValue(), subcommand.getRange()) + : null; + + return { + type: "HealthcheckInstruction", + keyword: "HEALTHCHECK", + flags: convertFlags(instruction), + subcommand: subcommandNode, + arguments: subcommandNode + ? args.filter( + argument => argument.start > subcommandNode.start, + ) + : args, + ...span, + }; + } + + if (instruction instanceof Onbuild) { + const trigger = instruction.getTriggerInstruction(); + + return { + type: "OnbuildInstruction", + keyword: "ONBUILD", + trigger: trigger ? convertInstruction(trigger) : null, + ...span, + }; + } + + if (instruction instanceof PropertyInstruction) { + const pairs = convertPairs(instruction); + + switch (keyword) { + case "ENV": + return { type: "EnvInstruction", keyword, pairs, ...span }; + case "ARG": + return { type: "ArgInstruction", keyword, pairs, ...span }; + case "LABEL": + return { + type: "LabelInstruction", + keyword, + pairs, + ...span, + }; + } + } + + if (instruction instanceof JSONInstruction) { + switch (keyword) { + case "RUN": + return { + type: "RunInstruction", + keyword, + flags: convertFlags(instruction), + command: convertCommandBody(instruction), + ...span, + }; + case "CMD": + return { + type: "CmdInstruction", + keyword, + command: convertCommandBody(instruction), + ...span, + }; + case "ENTRYPOINT": + return { + type: "EntrypointInstruction", + keyword, + command: convertCommandBody(instruction), + ...span, + }; + case "SHELL": { + return { + type: "ShellInstruction", + keyword, + command: instruction.getOpeningBracket() + ? convertExecForm(instruction) + : null, + ...span, + }; + } + case "COPY": + case "ADD": { + const args = instruction.getOpeningBracket() + ? convertJsonStrings(instruction) + : convertArguments(instruction); + const shared = { + keyword, + flags: convertFlags(instruction), + sources: args.slice(0, -1), + destination: args.at(-1) ?? null, + ...span, + }; + + return keyword === "COPY" + ? { type: "CopyInstruction", ...shared, keyword } + : { type: "AddInstruction", ...shared, keyword }; + } + case "VOLUME": + return { + type: "VolumeInstruction", + keyword, + paths: instruction.getOpeningBracket() + ? convertJsonStrings(instruction) + : convertArguments(instruction), + ...span, + }; + } + } + + const args = convertArguments(instruction); + + switch (keyword) { + case "WORKDIR": + return { + type: "WorkdirInstruction", + keyword, + path: args[0] ?? null, + ...span, + }; + case "USER": + return { + type: "UserInstruction", + keyword, + user: args[0] ?? null, + ...span, + }; + case "EXPOSE": + return { + type: "ExposeInstruction", + keyword, + ports: args, + ...span, + }; + case "STOPSIGNAL": + return { + type: "StopsignalInstruction", + keyword, + signal: args[0] ?? null, + ...span, + }; + case "MAINTAINER": + return { + type: "MaintainerInstruction", + keyword, + arguments: args, + ...span, + }; + default: + return { + type: "GenericInstruction", + keyword, + arguments: args, + ...span, + }; + } + } + + const comments: CommentNode[] = dockerfile.getComments().map(comment => ({ + type: "Comment", + text: comment.getContent(), + ...spanOf(comment.getRange()), + })); + + const directives: ParserDirectiveNode[] = dockerfile + .getDirectives() + .map(directive => ({ + type: "ParserDirective", + name: directive.getName(), + value: directive.getValue(), + ...spanOf(directive.getRange()), + })); + + const ast: DockerfileNode = { + type: "Dockerfile", + body: dockerfile.getInstructions().map(convertInstruction), + comments, + directives, + start: 0, + end: text.length, + }; + + return { ast, comments }; +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..676ae27 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,328 @@ +/** + * @fileoverview Type definitions for the Dockerfile ESTree-style syntax tree + * and for rules operating on it. See docs/syntax-tree.md for the full + * documentation of the tree format. + * @author Claude Fable 5 + */ + +//------------------------------------------------------------------------------ +// Base +//------------------------------------------------------------------------------ + +/** + * Every node carries `start` and `end` character offsets into the source + * text (0-based, `end` exclusive). Nodes deliberately do not carry `range` + * or `loc` properties; use `sourceCode.getRange(node)` and + * `sourceCode.getLoc(node)` instead. + */ +export interface DockerNodeBase { + type: string; + start: number; + end: number; +} + +/** + * Properties shared by every instruction node. `keyword` is always the + * canonical uppercase form; the keyword as written occupies + * `[start, start + keyword.length)` in the source text. + */ +export interface InstructionBase extends DockerNodeBase { + keyword: string; +} + +//------------------------------------------------------------------------------ +// Root +//------------------------------------------------------------------------------ + +export interface DockerfileNode extends DockerNodeBase { + type: "Dockerfile"; + body: InstructionNode[]; + comments: CommentNode[]; + directives: ParserDirectiveNode[]; +} + +export interface CommentNode extends DockerNodeBase { + type: "Comment"; + + /** The comment text without the leading `#`, trimmed. */ + text: string; +} + +/** + * A parser directive such as `# syntax=docker/dockerfile:1` or + * `# escape=\``. Directives may only appear before the first instruction + * and are not part of the traversed tree. + */ +export interface ParserDirectiveNode extends DockerNodeBase { + type: "ParserDirective"; + name: string; + value: string; +} + +//------------------------------------------------------------------------------ +// Shared pieces +//------------------------------------------------------------------------------ + +/** + * A whitespace-delimited token. For arguments derived from a JSON (exec + * form) array, `value` is the parsed string content while the offsets + * still include the enclosing double quotes. + */ +export interface ArgumentNode extends DockerNodeBase { + type: "Argument"; + value: string; +} + +/** + * An instruction option such as `--platform=linux/amd64` or + * `--chown=node:node`. `name` excludes the `--` prefix; `value` is `null` + * when the flag has no `=`. + */ +export interface FlagNode extends DockerNodeBase { + type: "Flag"; + name: string; + value: string | null; +} + +/** + * A `name=value` pair used by ENV, LABEL, and ARG. `value` is `null` for + * valueless ARG declarations. The value string has surrounding quotes + * removed while the node offsets still include them. + */ +export interface KeyValuePairNode extends DockerNodeBase { + type: "KeyValuePair"; + key: ArgumentNode; + value: ArgumentNode | null; +} + +/** The base image reference of a FROM instruction. */ +export interface ImageReferenceNode extends DockerNodeBase { + type: "ImageReference"; + + /** The image name, including any registry prefix. */ + name: string; + + /** The tag after `:`, or `null` when not specified. */ + tag: string | null; + + /** The digest after `@`, or `null` when not specified. */ + digest: string | null; +} + +/** The stage name after `AS` in a FROM instruction. */ +export interface StageNameNode extends DockerNodeBase { + type: "StageName"; + name: string; +} + +/** + * A shell-form command (`RUN apt-get update`). `arguments` holds the + * whitespace-delimited tokens with line continuations already resolved. + */ +export interface ShellFormNode extends DockerNodeBase { + type: "ShellForm"; + arguments: ArgumentNode[]; +} + +/** + * An exec-form (JSON array) command (`CMD ["node", "app.js"]`). Each + * element's `value` is the parsed string content. + */ +export interface ExecFormNode extends DockerNodeBase { + type: "ExecForm"; + elements: ArgumentNode[]; +} + +export type CommandBodyNode = ShellFormNode | ExecFormNode; + +//------------------------------------------------------------------------------ +// Instructions +//------------------------------------------------------------------------------ + +export interface FromInstructionNode extends InstructionBase { + type: "FromInstruction"; + keyword: "FROM"; + flags: FlagNode[]; + image: ImageReferenceNode | null; + alias: StageNameNode | null; +} + +export interface RunInstructionNode extends InstructionBase { + type: "RunInstruction"; + keyword: "RUN"; + flags: FlagNode[]; + command: CommandBodyNode | null; +} + +export interface CmdInstructionNode extends InstructionBase { + type: "CmdInstruction"; + keyword: "CMD"; + command: CommandBodyNode | null; +} + +export interface EntrypointInstructionNode extends InstructionBase { + type: "EntrypointInstruction"; + keyword: "ENTRYPOINT"; + command: CommandBodyNode | null; +} + +export interface ShellInstructionNode extends InstructionBase { + type: "ShellInstruction"; + keyword: "SHELL"; + command: ExecFormNode | null; +} + +export interface CopyInstructionNode extends InstructionBase { + type: "CopyInstruction"; + keyword: "COPY"; + flags: FlagNode[]; + sources: ArgumentNode[]; + destination: ArgumentNode | null; +} + +export interface AddInstructionNode extends InstructionBase { + type: "AddInstruction"; + keyword: "ADD"; + flags: FlagNode[]; + sources: ArgumentNode[]; + destination: ArgumentNode | null; +} + +export interface EnvInstructionNode extends InstructionBase { + type: "EnvInstruction"; + keyword: "ENV"; + pairs: KeyValuePairNode[]; +} + +export interface ArgInstructionNode extends InstructionBase { + type: "ArgInstruction"; + keyword: "ARG"; + pairs: KeyValuePairNode[]; +} + +export interface LabelInstructionNode extends InstructionBase { + type: "LabelInstruction"; + keyword: "LABEL"; + pairs: KeyValuePairNode[]; +} + +export interface WorkdirInstructionNode extends InstructionBase { + type: "WorkdirInstruction"; + keyword: "WORKDIR"; + path: ArgumentNode | null; +} + +export interface UserInstructionNode extends InstructionBase { + type: "UserInstruction"; + keyword: "USER"; + user: ArgumentNode | null; +} + +export interface ExposeInstructionNode extends InstructionBase { + type: "ExposeInstruction"; + keyword: "EXPOSE"; + ports: ArgumentNode[]; +} + +export interface VolumeInstructionNode extends InstructionBase { + type: "VolumeInstruction"; + keyword: "VOLUME"; + paths: ArgumentNode[]; +} + +export interface StopsignalInstructionNode extends InstructionBase { + type: "StopsignalInstruction"; + keyword: "STOPSIGNAL"; + signal: ArgumentNode | null; +} + +export interface HealthcheckInstructionNode extends InstructionBase { + type: "HealthcheckInstruction"; + keyword: "HEALTHCHECK"; + flags: FlagNode[]; + + /** The `CMD` or `NONE` argument, or `null` when missing. */ + subcommand: ArgumentNode | null; + + /** The tokens after the subcommand. */ + arguments: ArgumentNode[]; +} + +export interface OnbuildInstructionNode extends InstructionBase { + type: "OnbuildInstruction"; + keyword: "ONBUILD"; + trigger: InstructionNode | null; +} + +export interface MaintainerInstructionNode extends InstructionBase { + type: "MaintainerInstruction"; + keyword: "MAINTAINER"; + arguments: ArgumentNode[]; +} + +/** Any instruction with a keyword this plugin does not model. */ +export interface GenericInstructionNode extends InstructionBase { + type: "GenericInstruction"; + arguments: ArgumentNode[]; +} + +export type InstructionNode = + | FromInstructionNode + | RunInstructionNode + | CmdInstructionNode + | EntrypointInstructionNode + | ShellInstructionNode + | CopyInstructionNode + | AddInstructionNode + | EnvInstructionNode + | ArgInstructionNode + | LabelInstructionNode + | WorkdirInstructionNode + | UserInstructionNode + | ExposeInstructionNode + | VolumeInstructionNode + | StopsignalInstructionNode + | HealthcheckInstructionNode + | OnbuildInstructionNode + | MaintainerInstructionNode + | GenericInstructionNode; + +/** The node types of every instruction node. */ +export const INSTRUCTION_TYPES = [ + "FromInstruction", + "RunInstruction", + "CmdInstruction", + "EntrypointInstruction", + "ShellInstruction", + "CopyInstruction", + "AddInstruction", + "EnvInstruction", + "ArgInstruction", + "LabelInstruction", + "WorkdirInstruction", + "UserInstruction", + "ExposeInstruction", + "VolumeInstruction", + "StopsignalInstruction", + "HealthcheckInstruction", + "OnbuildInstruction", + "MaintainerInstruction", + "GenericInstruction", +] as const; + +//------------------------------------------------------------------------------ +// Union of all nodes +//------------------------------------------------------------------------------ + +export type DockerNode = + | DockerfileNode + | CommentNode + | ParserDirectiveNode + | InstructionNode + | ArgumentNode + | FlagNode + | KeyValuePairNode + | ImageReferenceNode + | StageNameNode + | ShellFormNode + | ExecFormNode; From 6f6ef9c0aaccf4cd778bb83221daeb85246b54b9 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 11 Nov 2026 09:14:27 -0500 Subject: [PATCH 2/8] fix: keep whitespace in WORKDIR paths The path node now spans the entire WORKDIR operand instead of the first whitespace-delimited token, with line continuations removed from its value. Co-Authored-By: Claude Opus 5.5 --- src/parser/parse.spec.ts | 16 ++++++++++++++++ src/parser/parse.ts | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts index f72e9ed..415f00d 100644 --- a/src/parser/parse.spec.ts +++ b/src/parser/parse.spec.ts @@ -347,6 +347,22 @@ describe("parseDocker", () => { expect(stopsignal.signal?.value).toBe("SIGTERM"); }); + it("should keep whitespace in WORKDIR paths", () => { + const text = "WORKDIR /app/my project\n"; + const { ast } = parseDocker(text); + const path = (ast.body[0] as WorkdirInstructionNode).path; + + expect(path?.value).toBe("/app/my project"); + expect(text.slice(path?.start, path?.end)).toBe("/app/my project"); + }); + + it("should join WORKDIR paths across line continuations", () => { + const { ast } = parseDocker("WORKDIR /app/my\\\nproject\n"); + const path = (ast.body[0] as WorkdirInstructionNode).path; + + expect(path?.value).toBe("/app/myproject"); + }); + it("should handle missing arguments", () => { const { ast } = parseDocker("WORKDIR\nUSER\n"); diff --git a/src/parser/parse.ts b/src/parser/parse.ts index f84cba4..fbbb916 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -74,6 +74,13 @@ function createPositionConverter( }; } +/** + * Escapes a string for literal use inside a regular expression. + */ +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +} + /** * Parses Dockerfile source code into an ESTree-style syntax tree. The * underlying parser is error-tolerant, so parsing never throws: malformed @@ -82,6 +89,10 @@ function createPositionConverter( export function parseDocker(text: string): DockerParseResult { const dockerfile = DockerfileParser.parse(text); const offsetAt = createPositionConverter(text); + const continuationPattern = new RegExp( + `${escapeRegExp(dockerfile.getEscapeCharacter())}[ \\t]*\\r?\\n`, + "gu", + ); const spanOf = (range: Range): { start: number; end: number } => ({ start: offsetAt(range.start), @@ -175,6 +186,31 @@ export function parseDocker(text: string): DockerParseResult { return args.length > 0 ? convertShellForm(args) : null; } + /** + * Combines all arguments of an instruction that takes its entire + * remaining text as one value (such as WORKDIR, where a path may + * contain whitespace). The value is the source text from the first to + * the last argument with line continuations removed; offsets span the + * same text. + */ + function joinArguments(args: ArgumentNode[]): ArgumentNode | null { + const first = args[0]; + const last = args.at(-1); + + if (!first || !last) { + return null; + } + + return { + type: "Argument", + value: text + .slice(first.start, last.end) + .replace(continuationPattern, ""), + start: first.start, + end: last.end, + }; + } + function convertPairs( instruction: PropertyInstruction, ): KeyValuePairNode[] { @@ -348,7 +384,7 @@ export function parseDocker(text: string): DockerParseResult { return { type: "WorkdirInstruction", keyword, - path: args[0] ?? null, + path: joinArguments(args), ...span, }; case "USER": From 376b079504cc5c40f8b867f74472afdee9c559ad Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 11 Nov 2026 11:09:48 -0500 Subject: [PATCH 3/8] docs: format Dockerfile instructions as code Co-Authored-By: Claude Opus 5.5 --- docs/syntax-tree.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/syntax-tree.md b/docs/syntax-tree.md index 235b289..354d66e 100644 --- a/docs/syntax-tree.md +++ b/docs/syntax-tree.md @@ -121,7 +121,7 @@ FROM node:20 RUN echo hello && echo world ``` -### FROM +### `FROM` ```ts interface FromInstruction extends InstructionBase { @@ -148,7 +148,7 @@ interface StageName extends DockerNodeBase { A `FROM` that references an earlier build stage still produces an `ImageReference`; its `name` is the stage name. -### RUN, CMD, ENTRYPOINT, and SHELL +### `RUN`, `CMD`, `ENTRYPOINT`, and `SHELL` ```ts interface RunInstruction extends InstructionBase { @@ -177,7 +177,7 @@ interface ShellInstruction extends InstructionBase { } ``` -### COPY and ADD +### `COPY` and `ADD` Both forms (`COPY a b /dest` and `COPY ["a", "b", "/dest"]`) produce the same shape: the last argument is the destination and the rest are sources. @@ -200,7 +200,7 @@ interface AddInstruction extends InstructionBase { } ``` -### ENV, ARG, and LABEL +### `ENV`, `ARG`, and `LABEL` All three produce `pairs` of key/value nodes. The legacy space-separated form `ENV key value` produces one pair whose value spans the rest of the @@ -248,7 +248,7 @@ interface StopsignalInstruction extends InstructionBase { } ``` -### EXPOSE and VOLUME +### `EXPOSE` and `VOLUME` ```ts interface ExposeInstruction extends InstructionBase { @@ -264,7 +264,7 @@ interface VolumeInstruction extends InstructionBase { } ``` -### HEALTHCHECK +### `HEALTHCHECK` ```ts interface HealthcheckInstruction extends InstructionBase { @@ -276,10 +276,10 @@ interface HealthcheckInstruction extends InstructionBase { } ``` -### ONBUILD +### `ONBUILD` The trigger is a full nested instruction node starting at its own keyword, -so rules that visit instruction types also see ONBUILD triggers. +so rules that visit instruction types also see `ONBUILD` triggers. ```ts interface OnbuildInstruction extends InstructionBase { @@ -289,7 +289,7 @@ interface OnbuildInstruction extends InstructionBase { } ``` -### MAINTAINER and unknown instructions +### `MAINTAINER` and unknown instructions ```ts interface MaintainerInstruction extends InstructionBase { From bb1e742abf88f7a45c070e290eb73fc7ffb4950b Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 18 Nov 2026 10:42:33 -0500 Subject: [PATCH 4/8] fix: keep registries and join continued lines in FROM image parts dockerfile-ast drops the registry from the image name and returns the source spelling of the tag, digest, and stage name, including line continuations. Rebuild the full name and remove continuations so rules see the values Docker uses. Co-Authored-By: Claude Opus 5.5 --- src/parser/parse.spec.ts | 46 ++++++++++++++++++++++++++++++++++++++++ src/parser/parse.ts | 22 +++++++++++++++---- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts index 415f00d..16d3da3 100644 --- a/src/parser/parse.spec.ts +++ b/src/parser/parse.spec.ts @@ -132,6 +132,52 @@ describe("parseDocker", () => { expect(from.alias).toBeNull(); }); + it("should keep the registry in the image name", () => { + for (const [text, name, tag] of [ + [ + "FROM registry.example.com/base\n", + "registry.example.com/base", + null, + ], + [ + "FROM localhost:5000/team/app:1.2\n", + "localhost:5000/team/app", + "1.2", + ], + [ + "FROM docker.io/library/node:20\n", + "docker.io/library/node", + "20", + ], + ["FROM ghcr.io/org/app\n", "ghcr.io/org/app", null], + ["FROM org/app:1\n", "org/app", "1"], + ] as const) { + const from = parseDocker(text).ast + .body[0] as FromInstructionNode; + + expect(from.image).toMatchObject({ name, tag }); + } + }); + + it("should remove line continuations from image parts and aliases", () => { + const text = "FROM ghcr.io/org/ap\\\npp:lat\\\nest AS bu\\\nild\n"; + const from = parseDocker(text).ast.body[0] as FromInstructionNode; + + expect(from.image).toMatchObject({ + name: "ghcr.io/org/appp", + tag: "latest", + }); + expect(from.alias?.name).toBe("build"); + }); + + it("should remove continuations using the escape directive", () => { + const text = "# escape=`\nFROM node:2`\n0 AS a`\nb\n"; + const from = parseDocker(text).ast.body[0] as FromInstructionNode; + + expect(from.image?.tag).toBe("20"); + expect(from.alias?.name).toBe("ab"); + }); + it("should handle FROM without an image", () => { const { ast } = parseDocker("FROM\n"); const from = ast.body[0] as FromInstructionNode; diff --git a/src/parser/parse.ts b/src/parser/parse.ts index fbbb916..11ebd34 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -238,6 +238,16 @@ export function parseDocker(text: string): DockerParseResult { const imageRange = instruction.getImageRange(); const stageName = instruction.getBuildStage(); const stageRange = instruction.getBuildStageRange(); + const registry = instruction.getRegistry(); + const imageName = instruction.getImageName() ?? ""; + + // dockerfile-ast returns the source spelling of these parts, + // including line continuations, and drops the registry from + // the image name. + const joinLines = (value: T): T => + (value === null + ? value + : value.replace(continuationPattern, "")) as T; return { type: "FromInstruction", @@ -246,9 +256,13 @@ export function parseDocker(text: string): DockerParseResult { image: imageRange ? { type: "ImageReference", - name: instruction.getImageName() ?? "", - tag: instruction.getImageTag(), - digest: instruction.getImageDigest(), + name: joinLines( + registry === null + ? imageName + : `${registry}/${imageName}`, + ), + tag: joinLines(instruction.getImageTag()), + digest: joinLines(instruction.getImageDigest()), ...spanOf(imageRange), } : null, @@ -256,7 +270,7 @@ export function parseDocker(text: string): DockerParseResult { stageName !== null && stageRange ? { type: "StageName", - name: stageName, + name: joinLines(stageName), ...spanOf(stageRange), } : null, From 6f968ef0e9c9928f0be7ccdc29fcba4cf28b7a9c Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Fri, 20 Nov 2026 10:35:30 -0500 Subject: [PATCH 5/8] fix: address parser edge cases from review - Treat bracket-leading arguments as JSON form only when they form a complete JSON array of strings - Drop comment lines inside line continuations from joined values - Keep the tag when a registry port and a digest are both present - Take COPY and ADD sources and destination from the heredoc header - Do not convert a nested ONBUILD trigger - Document raw JSON element values and continued keywords - Link the syntax-tree guide by absolute URL from the README Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/syntax-tree.md | 6 +- src/parser/parse.spec.ts | 81 ++++++++++++++++++++++ src/parser/parse.ts | 140 ++++++++++++++++++++++++++++++++++----- src/types.ts | 13 ++-- 5 files changed, 217 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 204735c..cf88e42 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Requires Node.js `^20.19.0 || ^22.13.0 || >=24`. Tested with ESLint v10. ## Syntax tree -The tree format is documented in [docs/syntax-tree.md](docs/syntax-tree.md). +The tree format is documented in [docs/syntax-tree.md](https://github.com/eslint/docker/blob/main/docs/syntax-tree.md). Nodes carry `start`/`end` character offsets instead of `range`/`loc` properties; use `sourceCode.getRange(node)` and `sourceCode.getLoc(node)`. diff --git a/docs/syntax-tree.md b/docs/syntax-tree.md index 354d66e..6f6574e 100644 --- a/docs/syntax-tree.md +++ b/docs/syntax-tree.md @@ -65,8 +65,10 @@ instruction is part of its arguments. ## Instructions Every instruction node carries its canonical uppercase `keyword`. The -keyword as written (which may be lowercase) occupies -`[start, start + keyword.length)` in the source text. +keyword as written (which may be lowercase) usually occupies +`[start, start + keyword.length)` in the source text. A line continuation +inside the keyword makes it longer, so compare that slice against `keyword` +before editing it. ```ts interface InstructionBase extends DockerNodeBase { diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts index 16d3da3..0415eae 100644 --- a/src/parser/parse.spec.ts +++ b/src/parser/parse.spec.ts @@ -151,6 +151,16 @@ describe("parseDocker", () => { ], ["FROM ghcr.io/org/app\n", "ghcr.io/org/app", null], ["FROM org/app:1\n", "org/app", "1"], + [ + "FROM localhost:5000/team/app:1.2@sha256:abc\n", + "localhost:5000/team/app", + "1.2", + ], + [ + "FROM localhost:5000/team/app@sha256:abc\n", + "localhost:5000/team/app", + null, + ], ] as const) { const from = parseDocker(text).ast .body[0] as FromInstructionNode; @@ -249,6 +259,40 @@ describe("parseDocker", () => { expect(command.elements[0]).toMatchObject({ start: 5, end: 16 }); }); + it("should keep JSON escapes in exec form element values", () => { + const text = 'CMD ["a\\u0062"]\n'; + const cmd = parseDocker(text).ast.body[0] as CmdInstructionNode; + const command = cmd.command as ExecFormNode; + + expect(command.elements[0]).toMatchObject({ + value: "a\\u0062", + start: 5, + end: 14, + }); + }); + + it("should parse bracket-leading commands that are not JSON as shell form", () => { + for (const text of [ + "RUN [ -f /app/config ] && echo ready\n", + 'RUN ["echo", "unterminated"\n', + 'RUN ["echo", 1]\n', + 'RUN ["echo"] && true\n', + ]) { + const run = parseDocker(text).ast.body[0] as RunInstructionNode; + + expect(run.command?.type).toBe("ShellForm"); + } + + const run = parseDocker("RUN [ -f /app/config ] && echo ready\n") + .ast.body[0] as RunInstructionNode; + + expect( + (run.command as ShellFormNode).arguments.map( + argument => argument.value, + ), + ).toEqual(["[", "-f", "/app/config", "]", "&&", "echo", "ready"]); + }); + it("should have a null command for empty RUN", () => { const { ast } = parseDocker("RUN\n"); const run = ast.body[0] as RunInstructionNode; @@ -314,6 +358,25 @@ describe("parseDocker", () => { expect(add.destination?.value).toBe("/app/"); }); + it("should treat bracket-leading paths that are not JSON as plain form", () => { + const copy = parseDocker("COPY [ab].txt /dest/\n").ast + .body[0] as CopyInstructionNode; + + expect(copy.sources.map(source => source.value)).toEqual([ + "[ab].txt", + ]); + expect(copy.destination?.value).toBe("/dest/"); + }); + + it("should take sources and destination from the heredoc header", () => { + const text = "COPY < source.value)).toEqual(["< { const { ast } = parseDocker("COPY src/\n"); const copy = ast.body[0] as CopyInstructionNode; @@ -409,6 +472,16 @@ describe("parseDocker", () => { expect(path?.value).toBe("/app/myproject"); }); + it("should drop comment lines inside WORKDIR continuations", () => { + const text = "WORKDIR /app/\\\n# note\nsub\n"; + const path = ( + parseDocker(text).ast.body[0] as WorkdirInstructionNode + ).path; + + expect(path?.value).toBe("/app/sub"); + expect(path?.end).toBe(text.length - 1); + }); + it("should handle missing arguments", () => { const { ast } = parseDocker("WORKDIR\nUSER\n"); @@ -486,6 +559,14 @@ describe("parseDocker", () => { expect(trigger.destination?.value).toBe("/app"); }); + it("should not convert a nested ONBUILD trigger", () => { + const text = `${"ONBUILD ".repeat(5000)}RUN make\n`; + const onbuild = parseDocker(text).ast + .body[0] as OnbuildInstructionNode; + + expect(onbuild.trigger).toBeNull(); + }); + it("should handle a missing trigger", () => { const { ast } = parseDocker("ONBUILD\n"); const onbuild = ast.body[0] as OnbuildInstructionNode; diff --git a/src/parser/parse.ts b/src/parser/parse.ts index 11ebd34..684e2af 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -89,11 +89,23 @@ function escapeRegExp(value: string): string { export function parseDocker(text: string): DockerParseResult { const dockerfile = DockerfileParser.parse(text); const offsetAt = createPositionConverter(text); + const escapeCharacter = dockerfile.getEscapeCharacter(); + + // A line continuation, together with any full-line comments and empty + // lines that follow it: Docker removes those before it processes the + // instruction. const continuationPattern = new RegExp( - `${escapeRegExp(dockerfile.getEscapeCharacter())}[ \\t]*\\r?\\n`, + `${escapeRegExp(escapeCharacter)}[ \\t]*\\r?\\n(?:[ \\t]*(?:#[^\\n]*)?\\r?\\n)*`, "gu", ); + /** + * Returns the source text between two offsets with line continuations + * and the comment lines inside them removed. + */ + const logicalText = (start: number, end: number): string => + text.slice(start, end).replace(continuationPattern, ""); + const spanOf = (range: Range): { start: number; end: number } => ({ start: offsetAt(range.start), end: offsetAt(range.end), @@ -174,10 +186,45 @@ export function parseDocker(text: string): DockerParseResult { }; } + /** + * Determines whether an instruction uses the JSON (exec) form. Docker + * treats the arguments as JSON only when they form a complete JSON array + * of strings; anything else, such as `RUN [ -f /app ] && make`, is + * shell form even though it starts with a bracket. + */ + function isJsonForm(instruction: JSONInstruction): boolean { + const openingBracket = instruction.getOpeningBracket(); + const closingBracket = instruction.getClosingBracket(); + + if (!openingBracket || !closingBracket) { + return false; + } + + const start = offsetAt(openingBracket.getRange().start); + const end = offsetAt(closingBracket.getRange().end); + const argsRange = instruction.getArgumentsRange(); + + // The closing bracket must end the arguments. + if (argsRange && offsetAt(argsRange.end) !== end) { + return false; + } + + try { + const value: unknown = JSON.parse(logicalText(start, end)); + + return ( + Array.isArray(value) && + value.every(element => typeof element === "string") + ); + } catch { + return false; + } + } + function convertCommandBody( instruction: JSONInstruction, ): CommandBodyNode | null { - if (instruction.getOpeningBracket()) { + if (isJsonForm(instruction)) { return convertExecForm(instruction); } @@ -203,14 +250,47 @@ export function parseDocker(text: string): DockerParseResult { return { type: "Argument", - value: text - .slice(first.start, last.end) - .replace(continuationPattern, ""), + value: logicalText(first.start, last.end), start: first.start, end: last.end, }; } + /** + * Returns the arguments that belong to the instruction header. When + * the instruction uses a heredoc (`COPY < argument.value.startsWith("<<"))) { + return args; + } + + let headerEnd = instructionStart; + + for (;;) { + const newline = text.indexOf("\n", headerEnd); + + if (newline === -1) { + return args; + } + + headerEnd = newline + 1; + + const line = text.slice(instructionStart, newline).trimEnd(); + + if (!line.endsWith(escapeCharacter)) { + break; + } + } + + return args.filter(argument => argument.start < headerEnd); + } + function convertPairs( instruction: PropertyInstruction, ): KeyValuePairNode[] { @@ -249,6 +329,28 @@ export function parseDocker(text: string): DockerParseResult { ? value : value.replace(continuationPattern, "")) as T; + let name = joinLines( + registry === null ? imageName : `${registry}/${imageName}`, + ); + let tag = joinLines(instruction.getImageTag()); + const digest = joinLines(instruction.getImageDigest()); + + // With a digest present, dockerfile-ast mistakes a registry + // port for the tag separator and leaves the real tag in the + // name (`localhost:5000/app:1.2@sha256:...`). A tag separator + // can only follow the last path separator. + if (digest !== null && tag === null) { + const separator = name.lastIndexOf(":"); + + if ( + separator > name.lastIndexOf("/") && + !name.slice(separator).includes("}") + ) { + tag = name.slice(separator + 1); + name = name.slice(0, separator); + } + } + return { type: "FromInstruction", keyword: "FROM", @@ -256,13 +358,9 @@ export function parseDocker(text: string): DockerParseResult { image: imageRange ? { type: "ImageReference", - name: joinLines( - registry === null - ? imageName - : `${registry}/${imageName}`, - ), - tag: joinLines(instruction.getImageTag()), - digest: joinLines(instruction.getImageDigest()), + name, + tag, + digest, ...spanOf(imageRange), } : null, @@ -302,10 +400,15 @@ export function parseDocker(text: string): DockerParseResult { if (instruction instanceof Onbuild) { const trigger = instruction.getTriggerInstruction(); + // Docker does not allow ONBUILD as a trigger. Converting a nested + // ONBUILD would recurse once per repetition. return { type: "OnbuildInstruction", keyword: "ONBUILD", - trigger: trigger ? convertInstruction(trigger) : null, + trigger: + trigger && !(trigger instanceof Onbuild) + ? convertInstruction(trigger) + : null, ...span, }; } @@ -356,7 +459,7 @@ export function parseDocker(text: string): DockerParseResult { return { type: "ShellInstruction", keyword, - command: instruction.getOpeningBracket() + command: isJsonForm(instruction) ? convertExecForm(instruction) : null, ...span, @@ -364,9 +467,12 @@ export function parseDocker(text: string): DockerParseResult { } case "COPY": case "ADD": { - const args = instruction.getOpeningBracket() + const args = isJsonForm(instruction) ? convertJsonStrings(instruction) - : convertArguments(instruction); + : headerArguments( + convertArguments(instruction), + span.start, + ); const shared = { keyword, flags: convertFlags(instruction), @@ -383,7 +489,7 @@ export function parseDocker(text: string): DockerParseResult { return { type: "VolumeInstruction", keyword, - paths: instruction.getOpeningBracket() + paths: isJsonForm(instruction) ? convertJsonStrings(instruction) : convertArguments(instruction), ...span, diff --git a/src/types.ts b/src/types.ts index 676ae27..8c3e855 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,8 +23,10 @@ export interface DockerNodeBase { /** * Properties shared by every instruction node. `keyword` is always the - * canonical uppercase form; the keyword as written occupies - * `[start, start + keyword.length)` in the source text. + * canonical uppercase form. The keyword as written usually occupies + * `[start, start + keyword.length)` in the source text, but a line + * continuation inside the keyword (`R\` followed by `UN`) makes it longer; + * compare that slice against `keyword` before editing it. */ export interface InstructionBase extends DockerNodeBase { keyword: string; @@ -65,8 +67,9 @@ export interface ParserDirectiveNode extends DockerNodeBase { /** * A whitespace-delimited token. For arguments derived from a JSON (exec - * form) array, `value` is the parsed string content while the offsets - * still include the enclosing double quotes. + * form) array, `value` is the raw source text between the double quotes + * (JSON escapes such as `b` are not decoded) while the offsets still + * include the enclosing double quotes. */ export interface ArgumentNode extends DockerNodeBase { type: "Argument"; @@ -126,7 +129,7 @@ export interface ShellFormNode extends DockerNodeBase { /** * An exec-form (JSON array) command (`CMD ["node", "app.js"]`). Each - * element's `value` is the parsed string content. + * element's `value` is the raw text between the quotes. */ export interface ExecFormNode extends DockerNodeBase { type: "ExecForm"; From 1719d01fe5393d91d48e30d8d533fa90038d17f6 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Mon, 23 Nov 2026 14:00:08 -0500 Subject: [PATCH 6/8] fix: handle CR line endings and comments in continued heredoc headers Co-Authored-By: Claude Opus 5.5 --- src/parser/parse.spec.ts | 24 ++++++++++++++++++++++++ src/parser/parse.ts | 14 ++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts index 0415eae..bcfbb4a 100644 --- a/src/parser/parse.spec.ts +++ b/src/parser/parse.spec.ts @@ -56,6 +56,21 @@ describe("parseDocker", () => { expect(ast.end).toBe(text.length); }); + it.each([ + ["LF", "\n"], + ["CRLF", "\r\n"], + ["CR", "\r"], + ])("should compute offsets with %s line endings", (_, eol) => { + const text = `FROM alpine${eol}RUN echo hi${eol}`; + const { ast } = parseDocker(text); + + expect(ast.body.map(node => node.start)).toEqual([ + 0, + text.indexOf("RUN"), + ]); + expect(ast.body[1]?.end).toBe(text.indexOf("hi") + 2); + }); + describe("comments and directives", () => { it("should collect comments with offsets and stripped text", () => { const text = "# hello world\nFROM node:20\n"; @@ -377,6 +392,15 @@ describe("parseDocker", () => { expect(copy.end).toBe(text.length - 1); }); + it("should skip comment lines inside a continued heredoc header", () => { + const text = + "COPY < source.value)).toEqual(["< { const { ast } = parseDocker("COPY src/\n"); const copy = ast.body[0] as CopyInstructionNode; diff --git a/src/parser/parse.ts b/src/parser/parse.ts index 684e2af..c6e9f9f 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -60,7 +60,8 @@ function createPositionConverter( const lineStarts = [0]; for (let i = 0; i < text.length; i++) { - if (text[i] === "\n") { + // LF, CRLF, and a standalone CR each end a line. + if (text[i] === "\n" || (text[i] === "\r" && text[i + 1] !== "\n")) { lineStarts.push(i + 1); } } @@ -271,6 +272,7 @@ export function parseDocker(text: string): DockerParseResult { } let headerEnd = instructionStart; + let continued = false; for (;;) { const newline = text.indexOf("\n", headerEnd); @@ -279,13 +281,21 @@ export function parseDocker(text: string): DockerParseResult { return args; } + const line = text.slice(headerEnd, newline).trim(); + headerEnd = newline + 1; - const line = text.slice(instructionStart, newline).trimEnd(); + // Comment and empty lines inside a continuation are removed + // before the header is parsed, so they do not end it. + if (continued && (line === "" || line.startsWith("#"))) { + continue; + } if (!line.endsWith(escapeCharacter)) { break; } + + continued = true; } return args.filter(argument => argument.start < headerEnd); From 9bab45f50e97dace1fb599657d7b98b98fadac2d Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Tue, 24 Nov 2026 16:51:41 -0500 Subject: [PATCH 7/8] docs: explain shell-form token splitting and escape handling Co-Authored-By: Claude Fable 5.2 --- docs/syntax-tree.md | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/syntax-tree.md b/docs/syntax-tree.md index 6f6574e..4a246ec 100644 --- a/docs/syntax-tree.md +++ b/docs/syntax-tree.md @@ -110,9 +110,10 @@ interface ExecForm extends DockerNodeBase { `Argument` is used in several positions with slightly different value semantics: -- **Shell-form tokens** (`RUN echo hi`): `value` is the token exactly as - written, including any quotes. Tokens are split on whitespace only, so - `echo "a b"` produces the tokens `echo`, `"a`, and `b"`. +- **Shell-form tokens** (`RUN echo hi`): tokens are split on whitespace + only, and `value` keeps any quotes, so `echo "a b"` produces the tokens + `echo`, `"a`, and `b"`. See [Shell-form tokens](#shell-form-tokens) for + how escapes affect `value`. - **Exec-form elements** (`CMD ["a b"]`): `value` is the raw text between the double quotes (`a b`), while the offsets include the quotes. - **Key/value pairs** (`ENV a="b c"`): the pair's `value` argument has @@ -123,6 +124,37 @@ FROM node:20 RUN echo hello && echo world ``` +#### Shell-form tokens + +The parser does not interpret shell syntax. Docker itself passes a +shell-form command to the shell as a single string, and the quoting rules +depend on which shell runs it (`/bin/sh`, `cmd`, PowerShell, or whatever a +`SHELL` instruction selects), which the parser cannot know. Splitting on +whitespace alone makes no assumption about the shell, and keeping the +quotes means no information is lost: a rule that needs shell words can +apply the quoting rules it wants across the tokens. + +A token's `value` is not always its exact source text, because the +Dockerfile escape character (`\`, or `` ` `` when the `escape` directive +selects it) is processed first: + +| Source | Tokens | +| -------------------- | ----------------------------------------- | +| `"a b"` | `"a` and `b"` | +| `c\"d` | `c"d` | +| `g\\h` | `g\h` | +| `\$x` | `\$x` | +| `a\ b` | `a` and `b`; neither token covers the `\` | +| `"q\`, newline, `r"` | `"qr"`, spanning both lines | + +That is, the escape character is removed before most characters but kept +before `$`, an escaped space still separates tokens, and a line +continuation inside a token is removed from its `value`. + +To get a token's exact spelling, slice the source text with its `start` +and `end` offsets rather than reading `value`. To see what separates two +tokens (for example, an escaped space), slice the text between them. + ### `FROM` ```ts From f52d6840f7b90cbf2fee6a8e97b848e30e183605 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Tue, 24 Nov 2026 16:55:55 -0500 Subject: [PATCH 8/8] refactor: return comments only on the ast from parseDocker The comments array was returned both as ast.comments and as a separate comments property pointing to the same array. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/parser/parse.spec.ts | 10 ++++------ src/parser/parse.ts | 3 +-- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index cf88e42..a3c80b2 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ The parser is also exported directly: ```js import { parseDocker } from "@eslint/docker"; -const { ast, comments } = parseDocker("FROM node:20-alpine\n"); +const { ast } = parseDocker("FROM node:20-alpine\n"); ``` Parsing never fails: the underlying parser is error-tolerant, so malformed diff --git a/src/parser/parse.spec.ts b/src/parser/parse.spec.ts index bcfbb4a..c04da8f 100644 --- a/src/parser/parse.spec.ts +++ b/src/parser/parse.spec.ts @@ -35,7 +35,7 @@ import type { describe("parseDocker", () => { it("should produce an empty Dockerfile node for empty input", () => { - const { ast, comments } = parseDocker(""); + const { ast } = parseDocker(""); expect(ast).toEqual({ type: "Dockerfile", @@ -45,7 +45,6 @@ describe("parseDocker", () => { start: 0, end: 0, }); - expect(comments).toEqual([]); }); it("should span the whole text with the root node", () => { @@ -74,16 +73,15 @@ describe("parseDocker", () => { describe("comments and directives", () => { it("should collect comments with offsets and stripped text", () => { const text = "# hello world\nFROM node:20\n"; - const { ast, comments } = parseDocker(text); + const { ast } = parseDocker(text); - expect(comments).toHaveLength(1); - expect(comments[0]).toMatchObject({ + expect(ast.comments).toHaveLength(1); + expect(ast.comments[0]).toMatchObject({ type: "Comment", text: "hello world", start: 0, end: 13, }); - expect(ast.comments).toBe(comments); }); it("should treat leading pragmas as parser directives", () => { diff --git a/src/parser/parse.ts b/src/parser/parse.ts index c6e9f9f..8986f6e 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -47,7 +47,6 @@ interface Range { export interface DockerParseResult { ast: DockerfileNode; - comments: CommentNode[]; } /** @@ -579,5 +578,5 @@ export function parseDocker(text: string): DockerParseResult { end: text.length, }; - return { ast, comments }; + return { ast }; }