Skip to content

Commit

Permalink
Add AreChecksumsEqual (#398)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuatcasey committed Sep 21, 2022
1 parent 190426a commit cd69bd3
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
27 changes: 27 additions & 0 deletions cargo/are_checksums_equal.go
@@ -0,0 +1,27 @@
package cargo

import "strings"

// AreChecksumsEqual returns true only when the given checksums match, including algorithm.
// The algorithm is given the same way that "cargo.ConfigMetadataDependency".Checksum expects,
// as "algorithm:checksum". Only exact equality is allowed, although algorithm is only checked
// if present in both of the given checksums.
func AreChecksumsEqual(c1, c2 string) bool {
var algorithm1, algorithm2 string
split1 := strings.Split(c1, ":")
if len(split1) == 2 {
algorithm1 = split1[0]
c1 = split1[1]
} else if len(split1) > 2 {
return false
}
split2 := strings.Split(c2, ":")
if len(split2) == 2 {
algorithm2 = split2[0]
c2 = split2[1]
}
areAlgorithmsEqual := func(a1, a2 string) bool {
return a1 == "" || a2 == "" || a1 == a2
}
return areAlgorithmsEqual(algorithm1, algorithm2) && c1 == c2
}
46 changes: 46 additions & 0 deletions cargo/are_checksums_equal_test.go
@@ -0,0 +1,46 @@
package cargo_test

import (
"testing"

. "github.com/onsi/gomega"
"github.com/paketo-buildpacks/packit/v2/cargo"
"github.com/sclevine/spec"
)

func testAreChecksumsEqual(t *testing.T, context spec.G, it spec.S) {
var (
Expect = NewWithT(t).Expect
)

context("AreChecksumsEqual", func() {
type testCaseType struct {
c1 string
c2 string
expected bool
}

for _, testCase := range []testCaseType{
{"", "", true},
{"c", "c", true},
{"c", "c", true},
{"sha256:c", "c", true},
{"c", "sha256:c", true},
{"md5:c", "md5:c", true},
{":", ":", true},
{":c", ":c", true},
{"", "c", false},
{"c", "", false},
{"c", "z", false},
{"md5:c", "sha256:c", false},
{"md5:c:d", "md5:c:d", false},
{"md5:c", "md5:c:d", false},
{":", "::", false},
{":", ":::", false},
} {
it("will check result", func() {
Expect(cargo.AreChecksumsEqual(testCase.c1, testCase.c2)).To(Equal(testCase.expected))
})
}
})
}
1 change: 1 addition & 0 deletions cargo/init_test.go
Expand Up @@ -15,6 +15,7 @@ func TestUnitCargo(t *testing.T) {
suite("DirectoryDuplicator", testDirectoryDuplicator)
suite("Transport", testTransport)
suite("ValidatedReader", testValidatedReader)
suite("AreChecksumsEqual", testAreChecksumsEqual)
suite.Run(t)
}

Expand Down

0 comments on commit cd69bd3

Please sign in to comment.