Use sync.Once for loading ServerVersion (#456)

rename loadClientServerVersion -> loadServerVersion

use sync.Once for loading ServerVersion

Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/456
Reviewed-by: Andrew Thornton <art27@cantab.net>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-Authored-By: 6543 <6543@obermui.de>
Co-Committed-By: 6543 <6543@obermui.de>
This commit is contained in:
6543 2020-11-13 09:03:33 +08:00
parent aa13606bc6
commit 60293eb2d1
2 changed files with 28 additions and 40 deletions

View file

@ -28,17 +28,17 @@ func Version() string {
// Client represents a Gitea API client.
type Client struct {
url string
accessToken string
username string
password string
otp string
sudo string
debug bool
client *http.Client
ctx context.Context
serverVersion *version.Version
versionLock sync.RWMutex
url string
accessToken string
username string
password string
otp string
sudo string
debug bool
client *http.Client
ctx context.Context
serverVersion *version.Version
getVersionOnce sync.Once
}
// Response represents the gitea response

View file

@ -22,14 +22,8 @@ func (c *Client) ServerVersion() (string, *Response, error) {
// CheckServerVersionConstraint validates that the login's server satisfies a
// given version constraint such as ">= 1.11.0+dev"
func (c *Client) CheckServerVersionConstraint(constraint string) error {
c.versionLock.RLock()
if c.serverVersion == nil {
c.versionLock.RUnlock()
if err := c.loadClientServerVersion(); err != nil {
return err
}
} else {
c.versionLock.RUnlock()
if err := c.loadServerVersion(); err != nil {
return err
}
check, err := version.NewConstraint(constraint)
@ -51,14 +45,8 @@ var (
// checkServerVersionGreaterThanOrEqual is internally used to speed up things and ignore issues with prerelease
func (c *Client) checkServerVersionGreaterThanOrEqual(v *version.Version) error {
c.versionLock.RLock()
if c.serverVersion == nil {
c.versionLock.RUnlock()
if err := c.loadClientServerVersion(); err != nil {
return err
}
} else {
c.versionLock.RUnlock()
if err := c.loadServerVersion(); err != nil {
return err
}
if !c.serverVersion.GreaterThanOrEqual(v) {
@ -67,17 +55,17 @@ func (c *Client) checkServerVersionGreaterThanOrEqual(v *version.Version) error
return nil
}
// loadClientServerVersion init the serverVersion variable
func (c *Client) loadClientServerVersion() error {
c.versionLock.Lock()
defer c.versionLock.Unlock()
raw, _, err := c.ServerVersion()
if err != nil {
return err
}
if c.serverVersion, err = version.NewVersion(raw); err != nil {
return err
}
return nil
// loadServerVersion init the serverVersion variable
func (c *Client) loadServerVersion() (err error) {
c.getVersionOnce.Do(func() {
raw, _, err2 := c.ServerVersion()
if err2 != nil {
err = err2
return
}
if c.serverVersion, err = version.NewVersion(raw); err != nil {
return
}
})
return
}