diff --git a/README.md b/README.md index f886573..a3c80b2 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](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)`. + +The parser is also exported directly: + +```js +import { parseDocker } from "@eslint/docker"; + +const { ast } = 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..4a246ec --- /dev/null +++ b/docs/syntax-tree.md @@ -0,0 +1,376 @@ +# 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) 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 { + 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`): 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 + quotes removed from its string, while the offsets include them. + +```dockerfile +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 +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..c04da8f --- /dev/null +++ b/src/parser/parse.spec.ts @@ -0,0 +1,632 @@ +/** + * @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 } = parseDocker(""); + + expect(ast).toEqual({ + type: "Dockerfile", + body: [], + comments: [], + directives: [], + start: 0, + end: 0, + }); + }); + + 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); + }); + + 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"; + const { ast } = parseDocker(text); + + expect(ast.comments).toHaveLength(1); + expect(ast.comments[0]).toMatchObject({ + type: "Comment", + text: "hello world", + start: 0, + end: 13, + }); + }); + + 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 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"], + [ + "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; + + 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; + + 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 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; + + 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 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 text = + "COPY < source.value)).toEqual(["< { + 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 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 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"); + + 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 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; + + 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..8986f6e --- /dev/null +++ b/src/parser/parse.ts @@ -0,0 +1,582 @@ +/** + * @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; +} + +/** + * 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++) { + // 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); + } + } + + return position => { + const lineStart = lineStarts[ + Math.min(position.line, lineStarts.length - 1) + ] as number; + + return Math.min(lineStart + position.character, text.length); + }; +} + +/** + * 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 + * input still produces a tree. + */ +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(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), + }); + + 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, + }; + } + + /** + * 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 (isJsonForm(instruction)) { + return convertExecForm(instruction); + } + + const args = convertArguments(instruction); + + 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: 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; + let continued = false; + + for (;;) { + const newline = text.indexOf("\n", headerEnd); + + if (newline === -1) { + return args; + } + + const line = text.slice(headerEnd, newline).trim(); + + headerEnd = newline + 1; + + // 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); + } + + 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(); + 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; + + 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", + flags: convertFlags(instruction), + image: imageRange + ? { + type: "ImageReference", + name, + tag, + digest, + ...spanOf(imageRange), + } + : null, + alias: + stageName !== null && stageRange + ? { + type: "StageName", + name: joinLines(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(); + + // Docker does not allow ONBUILD as a trigger. Converting a nested + // ONBUILD would recurse once per repetition. + return { + type: "OnbuildInstruction", + keyword: "ONBUILD", + trigger: + trigger && !(trigger instanceof Onbuild) + ? 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: isJsonForm(instruction) + ? convertExecForm(instruction) + : null, + ...span, + }; + } + case "COPY": + case "ADD": { + const args = isJsonForm(instruction) + ? convertJsonStrings(instruction) + : headerArguments( + convertArguments(instruction), + span.start, + ); + 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: isJsonForm(instruction) + ? convertJsonStrings(instruction) + : convertArguments(instruction), + ...span, + }; + } + } + + const args = convertArguments(instruction); + + switch (keyword) { + case "WORKDIR": + return { + type: "WorkdirInstruction", + keyword, + path: joinArguments(args), + ...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 }; +} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..8c3e855 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,331 @@ +/** + * @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 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; +} + +//------------------------------------------------------------------------------ +// 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 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"; + 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 raw text between the quotes. + */ +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;