From 21f106e6647ce70d1d40df65cd85e2e86264d2f0 Mon Sep 17 00:00:00 2001 From: Máximo Cuadros Date: Sun, 10 May 2020 11:02:21 +0200 Subject: config: RefSpec.IsExactSHA1, validates if the refspec describes an exact SHA1 ref --- plumbing/hash.go | 10 ++++++++++ plumbing/hash_test.go | 6 ++++++ 2 files changed, 16 insertions(+) (limited to 'plumbing') diff --git a/plumbing/hash.go b/plumbing/hash.go index 637a425..afc602a 100644 --- a/plumbing/hash.go +++ b/plumbing/hash.go @@ -71,3 +71,13 @@ type HashSlice []Hash func (p HashSlice) Len() int { return len(p) } func (p HashSlice) Less(i, j int) bool { return bytes.Compare(p[i][:], p[j][:]) < 0 } func (p HashSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// IsHash returns true if the given string is a valid hash. +func IsHash(s string) bool { + if len(s) != 40 { + return false + } + + _, err := hex.DecodeString(s) + return err == nil +} diff --git a/plumbing/hash_test.go b/plumbing/hash_test.go index fc2428b..0f836b0 100644 --- a/plumbing/hash_test.go +++ b/plumbing/hash_test.go @@ -52,3 +52,9 @@ func (s *HashSuite) TestHashesSort(c *C) { c.Assert(i[0], Equals, NewHash("1111111111111111111111111111111111111111")) c.Assert(i[1], Equals, NewHash("2222222222222222222222222222222222222222")) } + +func (s *HashSuite) TestIsHash(c *C) { + c.Assert(IsHash("8ab686eafeb1f44702738c8b0f24f2567c36da6d"), Equals, true) + c.Assert(IsHash("foo"), Equals, false) + c.Assert(IsHash("zab686eafeb1f44702738c8b0f24f2567c36da6d"), Equals, false) +} -- cgit