Last active
July 5, 2021 06:26
-
-
Save developer-guy/d157706b49b4ba1fd6d0f235e114bc0f to your computer and use it in GitHub Desktop.
List images within the Dockerfile via go programmatically using Moby Buildkit's official parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"github.com/google/go-containerregistry/pkg/authn" | |
"github.com/google/go-containerregistry/pkg/name" | |
"github.com/google/go-containerregistry/pkg/v1/remote" | |
"github.com/moby/buildkit/frontend/dockerfile/parser" | |
) | |
func main() { | |
f := os.Args[1] | |
c, err := os.Open(f) | |
if err != nil { | |
panic(err) | |
} | |
defer c.Close() | |
stages, err := parser.Parse(c) | |
if err != nil { | |
panic(err) | |
} | |
stageNames := map[string]struct{}{} | |
for _, s := range stages.AST.Children { | |
if s.Value == "from" { | |
if _, ok := stageNames[s.Next.Value]; ok { | |
continue | |
} | |
ref, err := name.ParseReference(s.Next.Value) | |
if err != nil { | |
panic(err) | |
} | |
img, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) | |
if err != nil { | |
panic(err) | |
} | |
dgst, err := img.Digest() | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(ref.Context().Digest(dgst.String())) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment