Skip to content

Commit

Permalink
feat: allow getSingleTag to return later occurrences
Browse files Browse the repository at this point in the history
  • Loading branch information
shivjm committed Nov 7, 2021
1 parent e45de00 commit c1ecb37
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
12 changes: 9 additions & 3 deletions main.go
Expand Up @@ -48,7 +48,7 @@ func main() {
if query == "" {
fmt.Println(string(val))
} else {
tag, err := getSingleTag(images, query)
tag, err := getSingleTag(images, query, 0)

if err != nil {
log.Fatalf("Could not find image in Dockerfile: %s", query)
Expand Down Expand Up @@ -107,10 +107,16 @@ func getImages(commands []dockerfile.Command, unknownMarker string) []Image {
return images
}

func getSingleTag(images []Image, query string) (string, error) {
func getSingleTag(images []Image, query string, occurrence int) (string, error) {
found := 0

for _, i := range images {
if i.Name == query {
return i.Tag, nil
found += 1

if found >= occurrence {
return i.Tag, nil
}
}
}

Expand Down
23 changes: 15 additions & 8 deletions main_test.go
Expand Up @@ -30,14 +30,21 @@ func TestParsing(t *testing.T) {

func TestQuery(t *testing.T) {
cases := []struct {
query string
match bool
tag string
query string
occurrence int
match bool
tag string
}{
{query: "foo", match: false, tag: ""},
{query: "viaductoss/ksops", match: true, tag: "v3.0.0"},
{query: "golang", match: true, tag: "1.17.0-alpine"},
{query: "common", match: true, tag: "?"},
{query: "foo", occurrence: 0, match: false, tag: ""},
{query: "viaductoss/ksops", occurrence: 0, match: true, tag: "v3.0.0"},
{query: "golang", occurrence: 0, match: true, tag: "1.17.0-alpine"},
{query: "common", occurrence: 0, match: true, tag: "?"},
{query: "foo", occurrence: 1, match: false, tag: ""},
{query: "viaductoss/ksops", occurrence: 1, match: true, tag: "v3.0.0"},
{query: "golang", occurrence: 1, match: true, tag: "1.17.0-alpine"},
{query: "common", occurrence: 1, match: true, tag: "?"},
{query: "viaductoss/ksops", occurrence: 2, match: false, tag: ""},
{query: "common", occurrence: 3, match: true, tag: "?"},
}

commands, err := dockerfile.ParseFile("tests/Dockerfile.1")
Expand All @@ -49,7 +56,7 @@ func TestQuery(t *testing.T) {
tags := getImages(commands, "?")

for _, c := range cases {
result, err := getSingleTag(tags, c.query)
result, err := getSingleTag(tags, c.query, c.occurrence)

if c.match {
assert.NoError(t, err, "must match %v", c.query)
Expand Down

0 comments on commit c1ecb37

Please sign in to comment.