Set client version to lowest for compat if server version can't be recognized and return specific error (#612)

This is a possible resolution for gitea/tea#531

Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/612
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Reviewed-by: 6543 <6543@obermui.de>
Co-authored-by: John Olheiser <john+gitea@jolheiser.com>
Co-committed-by: John Olheiser <john+gitea@jolheiser.com>
This commit is contained in:
John Olheiser 2023-04-03 05:30:53 +08:00 committed by 6543
parent 846d53e967
commit 7511c6d3cd
2 changed files with 20 additions and 0 deletions

View file

@ -9,6 +9,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -67,6 +68,9 @@ func NewClient(url string, options ...ClientOption) (*Client, error) {
}
}
if err := client.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
if errors.As(err, &ErrUnknownVersion{}) {
return client, err
}
return nil, err
}

View file

@ -6,6 +6,7 @@ package gitea
import (
"fmt"
"strings"
"github.com/hashicorp/go-version"
)
@ -70,6 +71,16 @@ var (
version1_17_0 = version.Must(version.NewVersion("1.17.0"))
)
// ErrUnknownVersion is an unknown version from the API
type ErrUnknownVersion struct {
raw string
}
// Error fulfills error
func (e ErrUnknownVersion) Error() string {
return fmt.Sprintf("unknown version: %s", e.raw)
}
// checkServerVersionGreaterThanOrEqual is the canonical way in the SDK to check for versions for API compatibility reasons
func (c *Client) checkServerVersionGreaterThanOrEqual(v *version.Version) error {
if c.ignoreVersion {
@ -97,6 +108,11 @@ func (c *Client) loadServerVersion() (err error) {
return
}
if c.serverVersion, err = version.NewVersion(raw); err != nil {
if strings.TrimSpace(raw) != "" {
// Version was something, just not recognized
c.serverVersion = version1_11_0
err = ErrUnknownVersion{raw: raw}
}
return
}
})