Skip to content

Commit

Permalink
Correctly parse ONBUILD instructions
Browse files Browse the repository at this point in the history
Fixes #23
  • Loading branch information
ashb committed Mar 19, 2024
1 parent 1e379d0 commit 051a0cb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
31 changes: 23 additions & 8 deletions buildkit/internal/dockerfile/dockerfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,25 +85,30 @@ func Print(node *parser.Node) (string, error) {
}

func printNode(node *parser.Node, writer io.Writer) error {
var v string
v := fmtNode(node)

_, err := fmt.Fprintln(writer, v)
if err != nil {
return err
}
return nil
}

func fmtNode(node *parser.Node) (v string) {
// format per directive
switch node.Value {
switch strings.ToLower(node.Value) {
// all the commands that use parseMaybeJSON
// https://github.com/moby/buildkit/blob/2ec7d53b00f24624cda0adfbdceed982623a93b3/frontend/dockerfile/parser/parser.go#L152
case command.Cmd, command.Entrypoint, command.Run, command.Shell:
v = fmtCmd(node)
case command.Label:
v = fmtLabel(node)
case command.Onbuild:
v = fmtSubCommand(node)
default:
v = fmtDefault(node)
}

_, err := fmt.Fprintln(writer, v)
if err != nil {
return err
}
return nil
return v
}

func getCmd(n *parser.Node) []string {
Expand Down Expand Up @@ -153,6 +158,16 @@ func fmtCmd(node *parser.Node) string {
return strings.Join(cmd, " ")
}

func fmtSubCommand(node *parser.Node) string {
cmd := []string{strings.ToUpper(node.Value)}
if len(node.Flags) > 0 {
cmd = append(cmd, node.Flags...)
}

sub := node.Next.Children[0]
return strings.Join(cmd, " ") + " " + fmtCmd(sub)
}

func fmtDefault(node *parser.Node) string {
cmd := getCmd(node)
return strings.Join(cmd, " ")
Expand Down
17 changes: 17 additions & 0 deletions buildkit/internal/transform/transforms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,20 @@ FROM astro-runtime:7.0.0
preambleText, err := dockerfile.Print(preamble)
assert.Equal(t, expectedPreamble, preambleText)
}

func TestOnBuild(t *testing.T) {
testDockerfile := `# syntax=astronomer/astro-runtime
FROM quay.io/astronomer/astro-runtime:7.0.0
ONBUILD RUN echo "hi!"
`

expectedDockerfile := `ONBUILD RUN echo "hi!"
`

preamble, body, err := Transform([]byte(testDockerfile), nil)
require.NoError(t, err)
assert.NotNil(t, preamble)
assert.NotNil(t, body)
bodyText, err := dockerfile.Print(body)
assert.Equal(t, expectedDockerfile, bodyText)
}

0 comments on commit 051a0cb

Please sign in to comment.