Fix GetCombinedStatus() (#470) #471

Closed
6543 wants to merge 13 commits from 6543:backport_470-GetCombinedStatus into main
32 changed files with 422 additions and 93 deletions

@ -29,7 +29,7 @@ steps:
- echo "[server]" >> /tmp/conf/app.ini - echo "[server]" >> /tmp/conf/app.ini
- echo "ROOT_URL = http://gitea:3000" >> /tmp/conf/app.ini - echo "ROOT_URL = http://gitea:3000" >> /tmp/conf/app.ini
- gitea migrate -c /tmp/conf/app.ini - gitea migrate -c /tmp/conf/app.ini
- gitea admin create-user --username=test01 --password=test01 --email=test01@gitea.io --admin=true --must-change-password=false --access-token -c /tmp/conf/app.ini - gitea admin user create --username=test01 --password=test01 --email=test01@gitea.io --admin=true --must-change-password=false --access-token -c /tmp/conf/app.ini
- gitea web -c /tmp/conf/app.ini - gitea web -c /tmp/conf/app.ini
- name: testing - name: testing

@ -1,6 +1,27 @@
# Changelog # Changelog
## [v0.13.0](https://gitea.com/gitea/go-sdk/releases/tag/v0.13.0) - 2020-09-15 ## [v0.13.2](https://gitea.com/gitea/go-sdk/releases/tag/gitea/v0.13.2) - 2020-12-07
* BUGFIXES
* Use Predefind Versions & Compare Function (#442) (#446)
* ENHANCEMENTS
* Add Gitea2Gitea Migration Support (#454) (#455)
* Update CreateRepoOption struct (#445) (#447)
* Update CommitMeta Struct (#434) (#437)
## [v0.13.1](https://gitea.com/gitea/go-sdk/releases/tag/gitea/v0.13.1) - 2020-09-29
* FEATURES
* Add GetReleaseByTag (#427) (#430)
* BUGFIXES
* Return http Response on NotFound too (#428) (#429)
* ENHANCEMENTS
* Update Struct NotificationSubject (#424) (#425)
* Add Debug Mode (#422) (#423)
## [v0.13.0](https://gitea.com/gitea/go-sdk/releases/tag/gitea/v0.13.0) - 2020-09-15
* BREAKING * BREAKING
* Check Gitea Version Requirement (#419) * Check Gitea Version Requirement (#419)
@ -39,7 +60,7 @@
* File Create/Update/Delete detect DefaultBranch if Branch not set for old Versions (#352) * File Create/Update/Delete detect DefaultBranch if Branch not set for old Versions (#352)
* Improve Error Handling (#351) * Improve Error Handling (#351)
## [v0.12.2](https://gitea.com/gitea/go-sdk/releases/tag/v0.12.2) - 2020-09-05 ## [v0.12.2](https://gitea.com/gitea/go-sdk/releases/tag/gitea/v0.12.2) - 2020-09-05
* ENHANCEMENTS * ENHANCEMENTS
* Extend Notification Functions (#381) (#385) * Extend Notification Functions (#381) (#385)

@ -25,7 +25,7 @@ help:
.PHONY: clean .PHONY: clean
clean: clean:
rm -r -f test rm -r -f test
$(GO) clean -i ./... cd gitea && $(GO) clean -i ./...
.PHONY: fmt .PHONY: fmt
fmt: fmt:
@ -68,10 +68,10 @@ test-instance:
echo "DB_TYPE = sqlite3" >> ${WORK_DIR}/test/conf/app.ini; \ echo "DB_TYPE = sqlite3" >> ${WORK_DIR}/test/conf/app.ini; \
echo "[repository]" >> ${WORK_DIR}/test/conf/app.ini; \ echo "[repository]" >> ${WORK_DIR}/test/conf/app.ini; \
echo "ROOT = ${WORK_DIR}/test/data/" >> ${WORK_DIR}/test/conf/app.ini; \ echo "ROOT = ${WORK_DIR}/test/data/" >> ${WORK_DIR}/test/conf/app.ini; \
echo "[server]" >> /tmp/conf/app.ini; \ echo "[server]" >> ${WORK_DIR}/test/conf/app.ini; \
echo "ROOT_URL = ${GITEA_SDK_TEST_URL}" >> /tmp/conf/app.ini; \ echo "ROOT_URL = ${GITEA_SDK_TEST_URL}" >> ${WORK_DIR}/test/conf/app.ini; \
${WORK_DIR}/test/gitea-master migrate -c ${WORK_DIR}/test/conf/app.ini; \ ${WORK_DIR}/test/gitea-master migrate -c ${WORK_DIR}/test/conf/app.ini; \
${WORK_DIR}/test/gitea-master admin create-user --username=${GITEA_SDK_TEST_USERNAME} --password=${GITEA_SDK_TEST_PASSWORD} --email=test01@gitea.io --admin=true --must-change-password=false --access-token -c ${WORK_DIR}/test/conf/app.ini; \ ${WORK_DIR}/test/gitea-master admin user create --username=${GITEA_SDK_TEST_USERNAME} --password=${GITEA_SDK_TEST_PASSWORD} --email=test01@gitea.io --admin=true --must-change-password=false --access-token -c ${WORK_DIR}/test/conf/app.ini; \
${WORK_DIR}/test/gitea-master web -c ${WORK_DIR}/test/conf/app.ini ${WORK_DIR}/test/gitea-master web -c ${WORK_DIR}/test/conf/app.ini
.PHONY: bench .PHONY: bench

@ -25,7 +25,7 @@ type ListCronTaskOptions struct {
// ListCronTasks list available cron tasks // ListCronTasks list available cron tasks
func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, *Response, error) { func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
@ -36,7 +36,7 @@ func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, *Response,
// RunCronTasks run a cron task // RunCronTasks run a cron task
func (c *Client) RunCronTasks(task string) (*Response, error) { func (c *Client) RunCronTasks(task string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil) _, resp, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil)

@ -43,7 +43,7 @@ func TestAdminCronTasks(t *testing.T) {
tasks, _, err := c.ListCronTasks(ListCronTaskOptions{}) tasks, _, err := c.ListCronTasks(ListCronTaskOptions{})
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, tasks, 15) assert.Len(t, tasks, 16)
_, err = c.RunCronTasks(tasks[0].Name) _, err = c.RunCronTasks(tasks[0].Name)
assert.NoError(t, err) assert.NoError(t, err)
} }

@ -34,6 +34,7 @@ type Client struct {
password string password string
otp string otp string
sudo string sudo string
debug bool
client *http.Client client *http.Client
ctx context.Context ctx context.Context
serverVersion *version.Version serverVersion *version.Version
@ -55,7 +56,7 @@ func NewClient(url string, options ...func(*Client)) (*Client, error) {
for _, opt := range options { for _, opt := range options {
opt(client) opt(client)
} }
if err := client.CheckServerVersionConstraint(">=1.10"); err != nil { if err := client.checkServerVersionGreaterThanOrEqual(version1_10_0); err != nil {
return nil, err return nil, err
} }
return client, nil return client, nil
@ -135,7 +136,17 @@ func (c *Client) SetSudo(sudo string) {
c.sudo = sudo c.sudo = sudo
} }
// SetDebugMode is an option for NewClient to enable debug mode
func SetDebugMode() func(client *Client) {
return func(client *Client) {
client.debug = true
}
}
func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) { func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) {
if c.debug {
fmt.Printf("%s: %s\nBody: %v\n", method, c.url+path, body)
}
req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body) req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -147,10 +158,16 @@ func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *R
defer resp.Body.Close() defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) data, err := ioutil.ReadAll(resp.Body)
if c.debug {
fmt.Printf("Response: %v\n\n", resp)
}
return data, &Response{resp}, nil return data, &Response{resp}, nil
} }
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) { func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) {
if c.debug {
fmt.Printf("%s: %s\nHeader: %v\nBody: %s\n", method, c.url+"/api/v1"+path, header, body)
}
req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body) req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body)
if err != nil { if err != nil {
return nil, err return nil, err
@ -175,6 +192,9 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read
if err != nil { if err != nil {
return nil, err return nil, err
} }
if c.debug {
fmt.Printf("Response: %v\n\n", resp)
}
return &Response{resp}, nil return &Response{resp}, nil
} }
@ -217,7 +237,7 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re
func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) (*Response, error) { func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) (*Response, error) {
data, resp, err := c.getResponse(method, path, header, body) data, resp, err := c.getResponse(method, path, header, body)
if err != nil { if err != nil {
return nil, err return resp, err
} }
return resp, json.Unmarshal(data, obj) return resp, json.Unmarshal(data, obj)
} }

@ -3,6 +3,6 @@ module code.gitea.io/sdk/gitea
go 1.12 go 1.12
require ( require (
github.com/hashicorp/go-version v1.2.0 github.com/hashicorp/go-version v1.2.1
github.com/stretchr/testify v1.4.0 github.com/stretchr/testify v1.4.0
) )

@ -121,7 +121,7 @@ func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, *Response, error) {
link, _ := url.Parse("/repos/issues/search") link, _ := url.Parse("/repos/issues/search")
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if e := c.checkServerVersionGreaterThanOrEqual(version1_12_0); e != nil {
for i := 0; i < len(issues); i++ { for i := 0; i < len(issues); i++ {
if issues[i].Repository != nil { if issues[i].Repository != nil {
issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0] issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0]
@ -139,7 +139,7 @@ func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Iss
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues", owner, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues", owner, repo))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if e := c.checkServerVersionGreaterThanOrEqual(version1_12_0); e != nil {
for i := 0; i < len(issues); i++ { for i := 0; i < len(issues); i++ {
if issues[i].Repository != nil { if issues[i].Repository != nil {
issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0] issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0]
@ -153,7 +153,7 @@ func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Iss
func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, *Response, error) { func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, *Response, error) {
issue := new(Issue) issue := new(Issue)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue)
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil && issue.Repository != nil { if e := c.checkServerVersionGreaterThanOrEqual(version1_12_0); e != nil && issue.Repository != nil {
issue.Repository.Owner = strings.Split(issue.Repository.FullName, "/")[0] issue.Repository.Owner = strings.Split(issue.Repository.FullName, "/")[0]
} }
return issue, resp, err return issue, resp, err

@ -68,7 +68,7 @@ func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentO
// GetIssueComment get a comment for a given repo by id. // GetIssueComment get a comment for a given repo by id.
func (c *Client) GetIssueComment(owner, repo string, id int64) (*Comment, *Response, error) { func (c *Client) GetIssueComment(owner, repo string, id int64) (*Comment, *Response, error) {
comment := new(Comment) comment := new(Comment)
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return comment, nil, err return comment, nil, err
} }
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, id), nil, nil, &comment) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, id), nil, nil, &comment)

@ -71,7 +71,7 @@ func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label,
return nil, nil, err return nil, nil, err
} }
if len(opt.Color) == 6 { if len(opt.Color) == 6 {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
opt.Color = "#" + opt.Color opt.Color = "#" + opt.Color
} }
} }

@ -20,7 +20,7 @@ type Reaction struct {
// GetIssueReactions get a list reactions of an issue // GetIssueReactions get a list reactions of an issue
func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction, *Response, error) { func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
reactions := make([]*Reaction, 0, 10) reactions := make([]*Reaction, 0, 10)
@ -30,7 +30,7 @@ func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction
// GetIssueCommentReactions get a list of reactions from a comment of an issue // GetIssueCommentReactions get a list of reactions from a comment of an issue
func (c *Client) GetIssueCommentReactions(owner, repo string, commentID int64) ([]*Reaction, *Response, error) { func (c *Client) GetIssueCommentReactions(owner, repo string, commentID int64) ([]*Reaction, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
reactions := make([]*Reaction, 0, 10) reactions := make([]*Reaction, 0, 10)
@ -45,7 +45,7 @@ type editReactionOption struct {
// PostIssueReaction add a reaction to an issue // PostIssueReaction add a reaction to an issue
func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction string) (*Reaction, *Response, error) { func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction string) (*Reaction, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
reactionResponse := new(Reaction) reactionResponse := new(Reaction)
@ -61,7 +61,7 @@ func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction str
// DeleteIssueReaction remove a reaction from an issue // DeleteIssueReaction remove a reaction from an issue
func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction string) (*Response, error) { func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})
@ -74,7 +74,7 @@ func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction s
// PostIssueCommentReaction add a reaction to a comment of an issue // PostIssueCommentReaction add a reaction to a comment of an issue
func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Reaction, *Response, error) { func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Reaction, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
reactionResponse := new(Reaction) reactionResponse := new(Reaction)
@ -90,7 +90,7 @@ func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, r
// DeleteIssueCommentReaction remove a reaction from a comment of an issue // DeleteIssueCommentReaction remove a reaction from a comment of an issue
func (c *Client) DeleteIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Response, error) { func (c *Client) DeleteIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})

@ -11,7 +11,7 @@ import (
// GetIssueSubscribers get list of users who subscribed on an issue // GetIssueSubscribers get list of users who subscribed on an issue
func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User, *Response, error) { func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
subscribers := make([]*User, 0, 10) subscribers := make([]*User, 0, 10)
@ -21,7 +21,7 @@ func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User,
// AddIssueSubscription Subscribe user to issue // AddIssueSubscription Subscribe user to issue
func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) (*Response, error) { func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
status, resp, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) status, resp, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
@ -39,7 +39,7 @@ func (c *Client) AddIssueSubscription(owner, repo string, index int64, user stri
// DeleteIssueSubscription unsubscribe user from issue // DeleteIssueSubscription unsubscribe user from issue
func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) (*Response, error) { func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
@ -57,7 +57,7 @@ func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user s
// CheckIssueSubscription check if current user is subscribed to an issue // CheckIssueSubscription check if current user is subscribed to an issue
func (c *Client) CheckIssueSubscription(owner, repo string, index int64) (*WatchInfo, *Response, error) { func (c *Client) CheckIssueSubscription(owner, repo string, index int64) (*WatchInfo, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
wi := new(WatchInfo) wi := new(WatchInfo)

@ -27,7 +27,7 @@ type TrackedTime struct {
// GetUserTrackedTimes list tracked times of a user // GetUserTrackedTimes list tracked times of a user
func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, *Response, error) { func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
@ -37,7 +37,7 @@ func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime,
// GetRepoTrackedTimes list tracked times of a repository // GetRepoTrackedTimes list tracked times of a repository
func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, *Response, error) { func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
@ -47,7 +47,7 @@ func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, *Respo
// GetMyTrackedTimes list tracked times of the current user // GetMyTrackedTimes list tracked times of the current user
func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, *Response, error) { func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
@ -75,7 +75,7 @@ func (opt AddTimeOption) Validate() error {
// AddTime adds time to issue with the given index // AddTime adds time to issue with the given index
func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, *Response, error) { func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(); err != nil { if err := opt.Validate(); err != nil {
@ -99,7 +99,7 @@ type ListTrackedTimesOptions struct {
// ListTrackedTimes list tracked times of a single issue for a given repository // ListTrackedTimes list tracked times of a single issue for a given repository
func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrackedTimesOptions) ([]*TrackedTime, *Response, error) { func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrackedTimesOptions) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, nil, err return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
@ -110,7 +110,7 @@ func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrack
// ResetIssueTime reset tracked time of a single issue for a given repository // ResetIssueTime reset tracked time of a single issue for a given repository
func (c *Client) ResetIssueTime(owner, repo string, index int64) (*Response, error) { func (c *Client) ResetIssueTime(owner, repo string, index int64) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil)
@ -119,7 +119,7 @@ func (c *Client) ResetIssueTime(owner, repo string, index int64) (*Response, err
// DeleteTime delete a specific tracked time by id of a single issue for a given repository // DeleteTime delete a specific tracked time by id of a single issue for a given repository
func (c *Client) DeleteTime(owner, repo string, index, timeID int64) (*Response, error) { func (c *Client) DeleteTime(owner, repo string, index, timeID int64) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_11_0); err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil)

@ -8,6 +8,12 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"time" "time"
"github.com/hashicorp/go-version"
)
var (
version1_12_3, _ = version.NewVersion("1.12.3")
) )
// NotificationThread expose Notification on API // NotificationThread expose Notification on API
@ -23,10 +29,11 @@ type NotificationThread struct {
// NotificationSubject contains the notification subject (Issue/Pull/Commit) // NotificationSubject contains the notification subject (Issue/Pull/Commit)
type NotificationSubject struct { type NotificationSubject struct {
Title string `json:"title"` Title string `json:"title"`
URL string `json:"url"` URL string `json:"url"`
LatestCommentURL string `json:"latest_comment_url"` LatestCommentURL string `json:"latest_comment_url"`
Type string `json:"type" binding:"In(Issue,Pull,Commit)"` Type string `json:"type"`
State StateType `json:"state"`
} }
// NotifyStatus notification status type // NotifyStatus notification status type
@ -74,7 +81,7 @@ func (opt *ListNotificationOptions) QueryEncode() string {
// Validate the CreateUserOption struct // Validate the CreateUserOption struct
func (opt ListNotificationOptions) Validate(c *Client) error { func (opt ListNotificationOptions) Validate(c *Client) error {
if len(opt.Status) != 0 { if len(opt.Status) != 0 {
return c.CheckServerVersionConstraint(">=1.12.3") return c.checkServerVersionGreaterThanOrEqual(version1_12_3)
} }
return nil return nil
} }
@ -97,14 +104,14 @@ func (opt *MarkNotificationOptions) QueryEncode() string {
// Validate the CreateUserOption struct // Validate the CreateUserOption struct
func (opt MarkNotificationOptions) Validate(c *Client) error { func (opt MarkNotificationOptions) Validate(c *Client) error {
if len(opt.Status) != 0 || len(opt.ToStatus) != 0 { if len(opt.Status) != 0 || len(opt.ToStatus) != 0 {
return c.CheckServerVersionConstraint(">=1.12.3") return c.checkServerVersionGreaterThanOrEqual(version1_12_3)
} }
return nil return nil
} }
// CheckNotifications list users's notification threads // CheckNotifications list users's notification threads
func (c *Client) CheckNotifications() (int64, *Response, error) { func (c *Client) CheckNotifications() (int64, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return 0, nil, err return 0, nil, err
} }
new := struct { new := struct {
@ -117,7 +124,7 @@ func (c *Client) CheckNotifications() (int64, *Response, error) {
// GetNotification get notification thread by ID // GetNotification get notification thread by ID
func (c *Client) GetNotification(id int64) (*NotificationThread, *Response, error) { func (c *Client) GetNotification(id int64) (*NotificationThread, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
thread := new(NotificationThread) thread := new(NotificationThread)
@ -128,7 +135,7 @@ func (c *Client) GetNotification(id int64) (*NotificationThread, *Response, erro
// ReadNotification mark notification thread as read by ID // ReadNotification mark notification thread as read by ID
// It optionally takes a second argument if status has to be set other than 'read' // It optionally takes a second argument if status has to be set other than 'read'
func (c *Client) ReadNotification(id int64, status ...NotifyStatus) (*Response, error) { func (c *Client) ReadNotification(id int64, status ...NotifyStatus) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
link := fmt.Sprintf("/notifications/threads/%d", id) link := fmt.Sprintf("/notifications/threads/%d", id)
@ -141,7 +148,7 @@ func (c *Client) ReadNotification(id int64, status ...NotifyStatus) (*Response,
// ListNotifications list users's notification threads // ListNotifications list users's notification threads
func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, *Response, error) { func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(c); err != nil { if err := opt.Validate(c); err != nil {
@ -156,7 +163,7 @@ func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*Notification
// ReadNotifications mark notification threads as read // ReadNotifications mark notification threads as read
func (c *Client) ReadNotifications(opt MarkNotificationOptions) (*Response, error) { func (c *Client) ReadNotifications(opt MarkNotificationOptions) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
if err := opt.Validate(c); err != nil { if err := opt.Validate(c); err != nil {
@ -170,7 +177,7 @@ func (c *Client) ReadNotifications(opt MarkNotificationOptions) (*Response, erro
// ListRepoNotifications list users's notification threads on a specific repo // ListRepoNotifications list users's notification threads on a specific repo
func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, *Response, error) { func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(c); err != nil { if err := opt.Validate(c); err != nil {
@ -185,7 +192,7 @@ func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificat
// ReadRepoNotifications mark notification threads as read on a specific repo // ReadRepoNotifications mark notification threads as read on a specific repo
func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) (*Response, error) { func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
if err := opt.Validate(c); err != nil { if err := opt.Validate(c); err != nil {

@ -34,7 +34,7 @@ type CreateOauth2Option struct {
// CreateOauth2 create an Oauth2 Application and returns a completed Oauth2 object. // CreateOauth2 create an Oauth2 Application and returns a completed Oauth2 object.
func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, *Response, error) { func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
@ -48,7 +48,7 @@ func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, *Response, error
// UpdateOauth2 a specific Oauth2 Application by ID and return a completed Oauth2 object. // UpdateOauth2 a specific Oauth2 Application by ID and return a completed Oauth2 object.
func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, *Response, error) { func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
@ -62,7 +62,7 @@ func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2,
// GetOauth2 a specific Oauth2 Application by ID. // GetOauth2 a specific Oauth2 Application by ID.
func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, *Response, error) { func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
oauth2s := &Oauth2{} oauth2s := &Oauth2{}
@ -72,7 +72,7 @@ func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, *Response, error) {
// ListOauth2 all of your Oauth2 Applications. // ListOauth2 all of your Oauth2 Applications.
func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, *Response, error) { func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
@ -83,7 +83,7 @@ func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, *Response, error)
// DeleteOauth2 delete an Oauth2 application by ID // DeleteOauth2 delete an Oauth2 application by ID
func (c *Client) DeleteOauth2(oauth2id int64) (*Response, error) { func (c *Client) DeleteOauth2(oauth2id int64) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil)

@ -160,7 +160,7 @@ func (opt EditPullRequestOption) Validate(c *Client) error {
return fmt.Errorf("title is empty") return fmt.Errorf("title is empty")
} }
if len(opt.Base) != 0 { if len(opt.Base) != 0 {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return fmt.Errorf("can not change base gitea to old") return fmt.Errorf("can not change base gitea to old")
} }
} }
@ -229,7 +229,7 @@ func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, *Re
// getPullRequestDiffOrPatch gets the patch or diff file as bytes for a PR // getPullRequestDiffOrPatch gets the patch or diff file as bytes for a PR
func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64) ([]byte, *Response, error) { func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64) ([]byte, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
r, _, err2 := c.GetRepo(owner, repo) r, _, err2 := c.GetRepo(owner, repo)
if err2 != nil { if err2 != nil {
return nil, nil, err return nil, nil, err

@ -132,7 +132,7 @@ func (opt CreatePullReviewComment) Validate() error {
// ListPullReviews lists all reviews of a pull request // ListPullReviews lists all reviews of a pull request
func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, *Response, error) { func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
@ -147,7 +147,7 @@ func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullRe
// GetPullReview gets a specific review of a pull request // GetPullReview gets a specific review of a pull request
func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview, *Response, error) { func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
@ -158,7 +158,7 @@ func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview
// ListPullReviewComments lists all comments of a pull request review // ListPullReviewComments lists all comments of a pull request review
func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]*PullReviewComment, *Response, error) { func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]*PullReviewComment, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
rcl := make([]*PullReviewComment, 0, 4) rcl := make([]*PullReviewComment, 0, 4)
@ -170,7 +170,7 @@ func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]
// DeletePullReview delete a specific review from a pull request // DeletePullReview delete a specific review from a pull request
func (c *Client) DeletePullReview(owner, repo string, index, id int64) (*Response, error) { func (c *Client) DeletePullReview(owner, repo string, index, id int64) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
@ -180,7 +180,7 @@ func (c *Client) DeletePullReview(owner, repo string, index, id int64) (*Respons
// CreatePullReview create a review to an pull request // CreatePullReview create a review to an pull request
func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePullReviewOptions) (*PullReview, *Response, error) { func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePullReviewOptions) (*PullReview, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(); err != nil { if err := opt.Validate(); err != nil {
@ -200,7 +200,7 @@ func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePul
// SubmitPullReview submit a pending review to an pull request // SubmitPullReview submit a pending review to an pull request
func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt SubmitPullReviewOptions) (*PullReview, *Response, error) { func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt SubmitPullReviewOptions) (*PullReview, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(); err != nil { if err := opt.Validate(); err != nil {

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http"
"strings" "strings"
"time" "time"
) )
@ -45,11 +46,23 @@ func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Re
return releases, resp, err return releases, resp, err
} }
// GetRelease get a release of a repository // GetRelease get a release of a repository by id
func (c *Client) GetRelease(user, repo string, id int64) (*Release, *Response, error) { func (c *Client) GetRelease(user, repo string, id int64) (*Release, *Response, error) {
r := new(Release) r := new(Release)
resp, err := c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id),
jsonHeader, nil, &r)
return r, resp, err
}
// GetReleaseByTag get a release of a repository by tag
func (c *Client) GetReleaseByTag(user, repo string, tag string) (*Release, *Response, error) {
if c.checkServerVersionGreaterThanOrEqual(version1_13_0) != nil {
return c.fallbackGetReleaseByTag(user, repo, tag)
}
r := new(Release)
resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases/tags/%s", user, repo, tag),
nil, nil, &r) nil, nil, &r)
return r, resp, err return r, resp, err
} }
@ -118,3 +131,23 @@ func (c *Client) DeleteRelease(user, repo string, id int64) (*Response, error) {
nil, nil) nil, nil)
return resp, err return resp, err
} }
// fallbackGetReleaseByTag is fallback for old gitea installations ( < 1.13.0 )
func (c *Client) fallbackGetReleaseByTag(user, repo string, tag string) (*Release, *Response, error) {
for i := 1; ; i++ {
rl, resp, err := c.ListReleases(user, repo, ListReleasesOptions{ListOptions{Page: i}})
if err != nil {
return nil, resp, err
}
if len(rl) == 0 {
return nil,
&Response{&http.Response{StatusCode: 404}},
fmt.Errorf("release with tag '%s' not found", tag)
}
for _, r := range rl {
if r.TagName == tag {
return r, resp, nil
}
}
}
}

95
gitea/release_test.go Normal file

@ -0,0 +1,95 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gitea
import (
"fmt"
"log"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRelease(t *testing.T) {
log.Println("== TestRelease ==")
c := newTestClient()
repo, _ := createTestRepo(t, "ReleaseTests", c)
// ListReleases
rl, _, err := c.ListReleases(repo.Owner.UserName, repo.Name, ListReleasesOptions{})
assert.NoError(t, err)
assert.Len(t, rl, 0)
// CreateRelease
r, _, err := c.CreateRelease(repo.Owner.UserName, repo.Name, CreateReleaseOption{
TagName: "awesome",
Target: "master",
Title: "Release 1",
Note: "yes it's awesome",
IsDraft: true,
IsPrerelease: true,
})
assert.NoError(t, err)
assert.EqualValues(t, "awesome", r.TagName)
assert.EqualValues(t, true, r.IsPrerelease)
assert.EqualValues(t, true, r.IsDraft)
assert.EqualValues(t, "Release 1", r.Title)
assert.EqualValues(t, fmt.Sprintf("%s/api/v1/repos/%s/releases/%d", c.url, repo.FullName, r.ID), r.URL)
assert.EqualValues(t, "master", r.Target)
assert.EqualValues(t, "yes it's awesome", r.Note)
assert.EqualValues(t, c.username, r.Publisher.UserName)
rl, _, _ = c.ListReleases(repo.Owner.UserName, repo.Name, ListReleasesOptions{})
assert.Len(t, rl, 1)
// GetRelease
r2, _, err := c.GetRelease(repo.Owner.UserName, repo.Name, r.ID)
assert.NoError(t, err)
assert.EqualValues(t, r, r2)
r2, _, err = c.GetReleaseByTag(repo.Owner.UserName, repo.Name, r.TagName)
assert.NoError(t, err)
assert.EqualValues(t, r, r2)
// test fallback
r2, _, err = c.fallbackGetReleaseByTag(repo.Owner.UserName, repo.Name, r.TagName)
assert.NoError(t, err)
assert.EqualValues(t, r, r2)
// EditRelease
bFalse := false
r2, _, err = c.EditRelease(repo.Owner.UserName, repo.Name, r.ID, EditReleaseOption{
Title: "Release Awesome",
Note: "",
IsDraft: &bFalse,
IsPrerelease: &bFalse,
})
assert.NoError(t, err)
assert.EqualValues(t, r.Target, r2.Target)
assert.EqualValues(t, bFalse, r2.IsDraft)
assert.EqualValues(t, bFalse, r2.IsPrerelease)
assert.EqualValues(t, r.Note, r2.Note)
// DeleteRelease
_, err = c.DeleteRelease(repo.Owner.UserName, repo.Name, r.ID)
assert.NoError(t, err)
rl, _, _ = c.ListReleases(repo.Owner.UserName, repo.Name, ListReleasesOptions{})
assert.Len(t, rl, 0)
// Test Response if try to get not existing release
_, resp, err := c.GetRelease(repo.Owner.UserName, repo.Name, 1234)
assert.Error(t, err)
if assert.NotNil(t, resp) {
assert.EqualValues(t, 404, resp.StatusCode)
}
_, resp, err = c.GetReleaseByTag(repo.Owner.UserName, repo.Name, "not_here")
assert.Error(t, err)
if assert.NotNil(t, resp) {
assert.EqualValues(t, 404, resp.StatusCode)
}
_, resp, err = c.fallbackGetReleaseByTag(repo.Owner.UserName, repo.Name, "not_here")
assert.Error(t, err)
if assert.NotNil(t, resp) {
assert.EqualValues(t, 404, resp.StatusCode)
}
}

@ -73,6 +73,20 @@ const (
RepoTypeMirror RepoType = "mirror" RepoTypeMirror RepoType = "mirror"
) )
// TrustModel represent how git signatures are handled in a repository
type TrustModel string
const (
// TrustModelDefault use TM set by global config
TrustModelDefault TrustModel = "default"
// TrustModelCollaborator gpg signature has to be owned by a repo collaborator
TrustModelCollaborator TrustModel = "collaborator"
// TrustModelCommitter gpg signature has to match committer
TrustModelCommitter TrustModel = "committer"
// TrustModelCollaboratorCommitter gpg signature has to match committer and owned by a repo collaborator
TrustModelCollaboratorCommitter TrustModel = "collaboratorcommitter"
)
// ListReposOptions options for listing repositories // ListReposOptions options for listing repositories
type ListReposOptions struct { type ListReposOptions struct {
ListOptions ListOptions
@ -224,7 +238,7 @@ func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, *Response, e
} else { } else {
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
// IsPrivate only works on gitea >= 1.12.0 // IsPrivate only works on gitea >= 1.12.0
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil && opt.IsPrivate != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil && opt.IsPrivate != nil {
if *opt.IsPrivate { if *opt.IsPrivate {
// private repos only not supported on gitea <= 1.11.x // private repos only not supported on gitea <= 1.11.x
return nil, nil, err return nil, nil, err
@ -249,6 +263,8 @@ type CreateRepoOption struct {
IssueLabels string `json:"issue_labels"` IssueLabels string `json:"issue_labels"`
// Whether the repository should be auto-intialized? // Whether the repository should be auto-intialized?
AutoInit bool `json:"auto_init"` AutoInit bool `json:"auto_init"`
// Whether the repository is template
Template bool `json:"template"`
// Gitignores to use // Gitignores to use
Gitignores string `json:"gitignores"` Gitignores string `json:"gitignores"`
// License to use // License to use
@ -257,19 +273,35 @@ type CreateRepoOption struct {
Readme string `json:"readme"` Readme string `json:"readme"`
// DefaultBranch of the repository (used when initializes and in template) // DefaultBranch of the repository (used when initializes and in template)
DefaultBranch string `json:"default_branch"` DefaultBranch string `json:"default_branch"`
// TrustModel of the repository
TrustModel TrustModel `json:"trust_model"`
} }
// Validate the CreateRepoOption struct // Validate the CreateRepoOption struct
func (opt CreateRepoOption) Validate() error { func (opt CreateRepoOption) Validate(c *Client) error {
if len(strings.TrimSpace(opt.Name)) == 0 { if len(strings.TrimSpace(opt.Name)) == 0 {
return fmt.Errorf("name is empty") return fmt.Errorf("name is empty")
} }
if len(opt.Name) > 100 {
return fmt.Errorf("name has more than 100 chars")
}
if len(opt.Description) > 255 {
return fmt.Errorf("name has more than 255 chars")
}
if len(opt.DefaultBranch) > 100 {
return fmt.Errorf("name has more than 100 chars")
}
if len(opt.TrustModel) != 0 {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return err
}
}
return nil return nil
} }
// CreateRepo creates a repository for authenticated user. // CreateRepo creates a repository for authenticated user.
func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, *Response, error) { func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil { if err := opt.Validate(c); err != nil {
return nil, nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
@ -283,7 +315,7 @@ func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, *Response, error
// CreateOrgRepo creates an organization repository for authenticated user. // CreateOrgRepo creates an organization repository for authenticated user.
func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, *Response, error) { func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil { if err := opt.Validate(c); err != nil {
return nil, nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)

@ -84,7 +84,7 @@ func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, *Response, e
// DeleteRepoBranch delete a branch in a repository // DeleteRepoBranch delete a branch in a repository
func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, *Response, error) { func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return false, nil, err return false, nil, err
} }
status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil) status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil)
@ -118,7 +118,7 @@ func (opt CreateBranchOption) Validate() error {
// CreateBranch creates a branch for a user's repository // CreateBranch creates a branch for a user's repository
func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, *Response, error) { func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := opt.Validate(); err != nil { if err := opt.Validate(); err != nil {

@ -92,7 +92,7 @@ type ListBranchProtectionsOptions struct {
// ListBranchProtections list branch protections for a repo // ListBranchProtections list branch protections for a repo
func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtectionsOptions) ([]*BranchProtection, *Response, error) { func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtectionsOptions) ([]*BranchProtection, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
bps := make([]*BranchProtection, 0, opt.PageSize) bps := make([]*BranchProtection, 0, opt.PageSize)
@ -104,7 +104,7 @@ func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtect
// GetBranchProtection gets a branch protection // GetBranchProtection gets a branch protection
func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, *Response, error) { func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
@ -114,7 +114,7 @@ func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtectio
// CreateBranchProtection creates a branch protection for a repo // CreateBranchProtection creates a branch protection for a repo
func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProtectionOption) (*BranchProtection, *Response, error) { func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProtectionOption) (*BranchProtection, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
@ -128,7 +128,7 @@ func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProt
// EditBranchProtection edits a branch protection for a repo // EditBranchProtection edits a branch protection for a repo
func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchProtectionOption) (*BranchProtection, *Response, error) { func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchProtectionOption) (*BranchProtection, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
@ -142,7 +142,7 @@ func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchPr
// DeleteBranchProtection deletes a branch protection for a repo // DeleteBranchProtection deletes a branch protection for a repo
func (c *Client) DeleteBranchProtection(owner, repo, name string) (*Response, error) { func (c *Client) DeleteBranchProtection(owner, repo, name string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil)

@ -19,8 +19,9 @@ type Identity struct {
// CommitMeta contains meta information of a commit in terms of API. // CommitMeta contains meta information of a commit in terms of API.
type CommitMeta struct { type CommitMeta struct {
URL string `json:"url"` URL string `json:"url"`
SHA string `json:"sha"` SHA string `json:"sha"`
Created time.Time `json:"created"`
} }
// CommitUser contains information of a user in the context of a commit. // CommitUser contains information of a user in the context of a commit.

@ -182,7 +182,7 @@ func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions)
func (c *Client) setDefaultBranchForOldVersions(owner, repo, branch string) (string, error) { func (c *Client) setDefaultBranchForOldVersions(owner, repo, branch string) (string, error) {
if len(branch) == 0 { if len(branch) == 0 {
// Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions // Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions
if c.CheckServerVersionConstraint(">=1.12.0") != nil { if c.checkServerVersionGreaterThanOrEqual(version1_12_0) != nil {
r, _, err := c.GetRepo(owner, repo) r, _, err := c.GetRepo(owner, repo)
if err != nil { if err != nil {
return "", err return "", err

@ -20,10 +20,10 @@ const (
GitServiceGithub GitServiceType = "github" GitServiceGithub GitServiceType = "github"
// GitServiceGitlab represents a gitlab service // GitServiceGitlab represents a gitlab service
GitServiceGitlab GitServiceType = "gitlab" GitServiceGitlab GitServiceType = "gitlab"
// GitServiceGitea represents a gitea service
GitServiceGitea GitServiceType = "gitea"
// Not supported jet // Not supported jet
// // GitServiceGitea represents a gitea service
// GitServiceGitea GitServiceType = "gitea"
// // GitServiceGogs represents a gogs service // // GitServiceGogs represents a gogs service
// GitServiceGogs GitServiceType = "gogs" // GitServiceGogs GitServiceType = "gogs"
) )
@ -51,7 +51,7 @@ type MigrateRepoOption struct {
} }
// Validate the MigrateRepoOption struct // Validate the MigrateRepoOption struct
func (opt *MigrateRepoOption) Validate() error { func (opt *MigrateRepoOption) Validate(c *Client) error {
// check user options // check user options
if len(opt.CloneAddr) == 0 { if len(opt.CloneAddr) == 0 {
return fmt.Errorf("CloneAddr required") return fmt.Errorf("CloneAddr required")
@ -69,6 +69,15 @@ func (opt *MigrateRepoOption) Validate() error {
if len(opt.AuthToken) == 0 { if len(opt.AuthToken) == 0 {
return fmt.Errorf("github require token authentication") return fmt.Errorf("github require token authentication")
} }
case GitServiceGitlab, GitServiceGitea:
if len(opt.AuthToken) == 0 {
return fmt.Errorf("%s require token authentication", opt.Service)
}
// Gitlab is supported since 1.12.0 but api cant handle it until 1.13.0
// https://github.com/go-gitea/gitea/pull/12672
if c.checkServerVersionGreaterThanOrEqual(version1_13_0) != nil {
return fmt.Errorf("migrate from service %s need gitea >= 1.13.0", opt.Service)
}
} }
return nil return nil
} }
@ -78,11 +87,11 @@ func (opt *MigrateRepoOption) Validate() error {
// To migrate a repository for a organization, the authenticated user must be a // To migrate a repository for a organization, the authenticated user must be a
// owner of the specified organization. // owner of the specified organization.
func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, *Response, error) { func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil { if err := opt.Validate(c); err != nil {
return nil, nil, err return nil, nil, err
} }
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
if len(opt.AuthToken) != 0 { if len(opt.AuthToken) != 0 {
// gitea <= 1.12 dont understand AuthToken // gitea <= 1.12 dont understand AuthToken
opt.AuthUsername = opt.AuthToken opt.AuthUsername = opt.AuthToken

@ -66,7 +66,7 @@ func TestRepoMigrateAndLanguages(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, lang, 2) assert.Len(t, lang, 2)
assert.True(t, 217441 < lang["Go"]) assert.True(t, 217441 < lang["Go"])
assert.EqualValues(t, 3578, lang["Makefile"]) assert.True(t, 3614 < lang["Makefile"] && 6000 > lang["Makefile"])
} }
func TestSearchRepo(t *testing.T) { func TestSearchRepo(t *testing.T) {

@ -20,7 +20,7 @@ type TransferRepoOption struct {
// TransferRepo transfers the ownership of a repository // TransferRepo transfers the ownership of a repository
func (c *Client) TransferRepo(owner, reponame string, opt TransferRepoOption) (*Repository, *Response, error) { func (c *Client) TransferRepo(owner, reponame string, opt TransferRepoOption) (*Repository, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_12_0); err != nil {
return nil, nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)

@ -33,7 +33,7 @@ type GlobalAttachmentSettings struct {
// GetGlobalUISettings get global ui settings witch are exposed by API // GetGlobalUISettings get global ui settings witch are exposed by API
func (c *Client) GetGlobalUISettings() (*GlobalUISettings, *Response, error) { func (c *Client) GetGlobalUISettings() (*GlobalUISettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
conf := new(GlobalUISettings) conf := new(GlobalUISettings)
@ -43,7 +43,7 @@ func (c *Client) GetGlobalUISettings() (*GlobalUISettings, *Response, error) {
// GetGlobalRepoSettings get global repository settings witch are exposed by API // GetGlobalRepoSettings get global repository settings witch are exposed by API
func (c *Client) GetGlobalRepoSettings() (*GlobalRepoSettings, *Response, error) { func (c *Client) GetGlobalRepoSettings() (*GlobalRepoSettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
conf := new(GlobalRepoSettings) conf := new(GlobalRepoSettings)
@ -53,7 +53,7 @@ func (c *Client) GetGlobalRepoSettings() (*GlobalRepoSettings, *Response, error)
// GetGlobalAPISettings get global api settings witch are exposed by it // GetGlobalAPISettings get global api settings witch are exposed by it
func (c *Client) GetGlobalAPISettings() (*GlobalAPISettings, *Response, error) { func (c *Client) GetGlobalAPISettings() (*GlobalAPISettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
conf := new(GlobalAPISettings) conf := new(GlobalAPISettings)
@ -63,7 +63,7 @@ func (c *Client) GetGlobalAPISettings() (*GlobalAPISettings, *Response, error) {
// GetGlobalAttachmentSettings get global repository settings witch are exposed by API // GetGlobalAttachmentSettings get global repository settings witch are exposed by API
func (c *Client) GetGlobalAttachmentSettings() (*GlobalAttachmentSettings, *Response, error) { func (c *Client) GetGlobalAttachmentSettings() (*GlobalAttachmentSettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { if err := c.checkServerVersionGreaterThanOrEqual(version1_13_0); err != nil {
return nil, nil, err return nil, nil, err
} }
conf := new(GlobalAttachmentSettings) conf := new(GlobalAttachmentSettings)

@ -40,7 +40,7 @@ func TestGetGlobalSettings(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, &GlobalAttachmentSettings{ assert.EqualValues(t, &GlobalAttachmentSettings{
Enabled: true, Enabled: true,
AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", AllowedTypes: ".docx,.gif,.gz,.jpeg,.jpg,.log,.pdf,.png,.pptx,.txt,.xlsx,.zip",
MaxSize: 4, MaxSize: 4,
MaxFiles: 5, MaxFiles: 5,
}, attachSettings) }, attachSettings)

@ -65,11 +65,11 @@ type ListStatusesOption struct {
ListOptions ListOptions
} }
// ListStatuses returns all statuses for a given Commit // ListStatuses returns all statuses for a given Commit by ref
func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, *Response, error) { func (c *Client) ListStatuses(owner, repo, ref string, opt ListStatusesOption) ([]*Status, *Response, error) {
opt.setDefaults() opt.setDefaults()
statuses := make([]*Status, 0, opt.PageSize) statuses := make([]*Status, 0, opt.PageSize)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?%s", owner, repo, sha, opt.getURLQuery().Encode()), nil, nil, &statuses) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?%s", owner, repo, ref, opt.getURLQuery().Encode()), jsonHeader, nil, &statuses)
return statuses, resp, err return statuses, resp, err
} }
@ -85,8 +85,14 @@ type CombinedStatus struct {
} }
// GetCombinedStatus returns the CombinedStatus for a given Commit // GetCombinedStatus returns the CombinedStatus for a given Commit
func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, *Response, error) { func (c *Client) GetCombinedStatus(owner, repo, ref string) (*CombinedStatus, *Response, error) {
status := new(CombinedStatus) status := new(CombinedStatus)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, sha), nil, nil, status) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, ref), jsonHeader, nil, status)
// gitea api return empty body if nothing here jet
if resp != nil && resp.StatusCode == 200 && err != nil {
return status, resp, nil
}
return status, resp, err return status, resp, err
} }

79
gitea/status_test.go Normal file

@ -0,0 +1,79 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gitea
import (
"log"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCommitStatus(t *testing.T) {
log.Println("== TestCommitStatus ==")
c := newTestClient()
user, _, err := c.GetMyUserInfo()
assert.NoError(t, err)
var repoName = "CommitStatuses"
origRepo, err := createTestRepo(t, repoName, c)
if !assert.NoError(t, err) {
return
}
commits, _, _ := c.ListRepoCommits(user.UserName, repoName, ListCommitOptions{
ListOptions: ListOptions{},
SHA: origRepo.DefaultBranch,
})
if !assert.Len(t, commits, 1) {
return
}
sha := commits[0].SHA
combiStats, resp, err := c.GetCombinedStatus(user.UserName, repoName, sha)
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, combiStats)
assert.EqualValues(t, 0, combiStats.TotalCount)
statuses, resp, err := c.ListStatuses(user.UserName, repoName, sha, ListStatusesOption{})
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, statuses)
assert.Len(t, statuses, 0)
createStatus(t, c, user.UserName, repoName, sha, "http://dummy.test", "start testing", "ultraCI", StatusPending)
createStatus(t, c, user.UserName, repoName, sha, "https://more.secure", "just a warning", "warn/bot", StatusWarning)
createStatus(t, c, user.UserName, repoName, sha, "http://dummy.test", "test failed", "ultraCI", StatusFailure)
createStatus(t, c, user.UserName, repoName, sha, "http://dummy.test", "start testing", "ultraCI", StatusPending)
createStatus(t, c, user.UserName, repoName, sha, "http://dummy.test", "test passed", "ultraCI", StatusSuccess)
statuses, resp, err = c.ListStatuses(user.UserName, repoName, sha, ListStatusesOption{})
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, statuses)
assert.Len(t, statuses, 5)
combiStats, resp, err = c.GetCombinedStatus(user.UserName, repoName, sha)
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, combiStats)
assert.EqualValues(t, 2, combiStats.TotalCount)
assert.EqualValues(t, StatusState("warning"), combiStats.State)
assert.Len(t, combiStats.Statuses, 2)
}
func createStatus(t *testing.T, c *Client, userName, repoName, sha, url, desc, context string, state StatusState) {
stats, resp, err := c.CreateStatus(userName, repoName, sha, CreateStatusOption{
State: state,
TargetURL: url,
Description: desc,
Context: context,
})
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, stats)
assert.EqualValues(t, state, stats.State)
}

@ -42,6 +42,32 @@ func (c *Client) CheckServerVersionConstraint(constraint string) error {
return nil return nil
} }
// predefined versions only have to be parsed by library once
var (
version1_10_0, _ = version.NewVersion("1.10.0")
version1_11_0, _ = version.NewVersion("1.11.0")
version1_12_0, _ = version.NewVersion("1.12.0")
version1_13_0, _ = version.NewVersion("1.13.0")
)
// 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 !c.serverVersion.GreaterThanOrEqual(v) {
return fmt.Errorf("gitea server at %s is older than %s", c.url, v.Original())
}
return nil
}
// loadClientServerVersion init the serverVersion variable // loadClientServerVersion init the serverVersion variable
func (c *Client) loadClientServerVersion() error { func (c *Client) loadClientServerVersion() error {
c.versionLock.Lock() c.versionLock.Lock()