From 9d7bd4d4bded83428a39dda358eef19e98e42f23 Mon Sep 17 00:00:00 2001 From: andrew2nelson Date: Wed, 2 Sep 2020 13:38:42 -0700 Subject: Fetch should return a unique error type when ref not found It can be useful for callers to distinguish between an error of "couldn't find remote ref" and some other error like "network error". Creating an explicit error type for this allows consumers to determine the kind of error using the errors.Is and errors.As interface added in go1.13 --- remote.go | 15 ++++++++++++++- remote_test.go | 2 ++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/remote.go b/remote.go index 89b3051..d88e8e6 100644 --- a/remote.go +++ b/remote.go @@ -32,6 +32,19 @@ var ( ErrExactSHA1NotSupported = errors.New("server does not support exact SHA1 refspec") ) +type NoMatchingRefSpecError struct { + refSpec config.RefSpec +} + +func (e NoMatchingRefSpecError) Error() string { + return fmt.Sprintf("couldn't find remote ref %q", e.refSpec.Src()) +} + +func (e NoMatchingRefSpecError) Is(target error) bool { + _, ok := target.(NoMatchingRefSpecError) + return ok +} + const ( // This describes the maximum number of commits to walk when // computing the haves to send to a server, for each ref in the @@ -751,7 +764,7 @@ func doCalculateRefs( }) if !matched && !s.IsWildcard() { - return fmt.Errorf("couldn't find remote ref %q", s.Src()) + return NoMatchingRefSpecError{refSpec: s} } return err diff --git a/remote_test.go b/remote_test.go index c6ea9ea..3446f1a 100644 --- a/remote_test.go +++ b/remote_test.go @@ -3,6 +3,7 @@ package git import ( "bytes" "context" + "errors" "io" "io/ioutil" "os" @@ -145,6 +146,7 @@ func (s *RemoteSuite) TestFetchNonExistantReference(c *C) { }) c.Assert(err, ErrorMatches, "couldn't find remote ref.*") + c.Assert(errors.Is(err, NoMatchingRefSpecError{}), Equals, true) } func (s *RemoteSuite) TestFetchContext(c *C) { -- cgit