Update SDK to v0.13.0 (#179)

check err

Notifications: Add Pinned Filter

migrate & adapt

update sdk to v0.13.0

Co-authored-by: 6543 <6543@obermui.de>
Reviewed-on: https://gitea.com/gitea/tea/pulls/179
Reviewed-by: techknowlogick <techknowlogick@gitea.io>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
6543 2020-09-16 02:01:41 +00:00 committed by Lunny Xiao
parent ed961c795e
commit f47ac8f96e
63 changed files with 2024 additions and 924 deletions

View File

@ -40,16 +40,23 @@ type Login struct {
// Client returns a client to operate Gitea API // Client returns a client to operate Gitea API
func (l *Login) Client() *gitea.Client { func (l *Login) Client() *gitea.Client {
client := gitea.NewClient(l.URL, l.Token) httpClient := &http.Client{}
if l.Insecure { if l.Insecure {
cookieJar, _ := cookiejar.New(nil) cookieJar, _ := cookiejar.New(nil)
client.SetHTTPClient(&http.Client{ httpClient = &http.Client{
Jar: cookieJar, Jar: cookieJar,
Transport: &http.Transport{ Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}, }}
}) }
client, err := gitea.NewClient(l.URL,
gitea.SetToken(l.Token),
gitea.SetHTTPClient(httpClient),
)
if err != nil {
log.Fatal(err)
} }
return client return client
} }

View File

@ -59,7 +59,7 @@ func runIssueDetail(ctx *cli.Context, index string) error {
if err != nil { if err != nil {
return err return err
} }
issue, err := login.Client().GetIssue(owner, repo, idx) issue, _, err := login.Client().GetIssue(owner, repo, idx)
if err != nil { if err != nil {
return err return err
} }
@ -86,7 +86,7 @@ func runIssuesList(ctx *cli.Context) error {
state = gitea.StateClosed state = gitea.StateClosed
} }
issues, err := login.Client().ListRepoIssues(owner, repo, gitea.ListIssueOption{ issues, _, err := login.Client().ListRepoIssues(owner, repo, gitea.ListIssueOption{
State: state, State: state,
Type: gitea.IssueTypeIssue, Type: gitea.IssueTypeIssue,
}) })
@ -154,7 +154,7 @@ var CmdIssuesCreate = cli.Command{
func runIssuesCreate(ctx *cli.Context) error { func runIssuesCreate(ctx *cli.Context) error {
login, owner, repo := initCommand() login, owner, repo := initCommand()
_, err := login.Client().CreateIssue(owner, repo, gitea.CreateIssueOption{ _, _, err := login.Client().CreateIssue(owner, repo, gitea.CreateIssueOption{
Title: ctx.String("title"), Title: ctx.String("title"),
Body: ctx.String("body"), Body: ctx.String("body"),
// TODO: // TODO:
@ -212,6 +212,6 @@ func editIssueState(ctx *cli.Context, opts gitea.EditIssueOption) error {
return err return err
} }
_, err = login.Client().EditIssue(owner, repo, index, opts) _, _, err = login.Client().EditIssue(owner, repo, index, opts)
return err return err
} }

View File

@ -49,7 +49,7 @@ func runLabels(ctx *cli.Context) error {
var values [][]string var values [][]string
labels, err := login.Client().ListRepoLabels(owner, repo, gitea.ListLabelsOptions{}) labels, _, err := login.Client().ListRepoLabels(owner, repo, gitea.ListLabelsOptions{})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -141,7 +141,7 @@ func runLabelCreate(ctx *cli.Context) error {
labelFile := ctx.String("file") labelFile := ctx.String("file")
var err error var err error
if len(labelFile) == 0 { if len(labelFile) == 0 {
_, err = login.Client().CreateLabel(owner, repo, gitea.CreateLabelOption{ _, _, err = login.Client().CreateLabel(owner, repo, gitea.CreateLabelOption{
Name: ctx.String("name"), Name: ctx.String("name"),
Color: ctx.String("color"), Color: ctx.String("color"),
Description: ctx.String("description"), Description: ctx.String("description"),
@ -162,7 +162,7 @@ func runLabelCreate(ctx *cli.Context) error {
if color == "" || name == "" { if color == "" || name == "" {
log.Printf("Line %d ignored because lack of enough fields: %s\n", i, line) log.Printf("Line %d ignored because lack of enough fields: %s\n", i, line)
} else { } else {
_, err = login.Client().CreateLabel(owner, repo, gitea.CreateLabelOption{ _, _, err = login.Client().CreateLabel(owner, repo, gitea.CreateLabelOption{
Name: name, Name: name,
Color: color, Color: color,
Description: description, Description: description,
@ -227,7 +227,7 @@ func runLabelUpdate(ctx *cli.Context) error {
} }
var err error var err error
_, err = login.Client().EditLabel(owner, repo, id, gitea.EditLabelOption{ _, _, err = login.Client().EditLabel(owner, repo, id, gitea.EditLabelOption{
Name: pName, Name: pName,
Color: pColor, Color: pColor,
Description: pDescription, Description: pDescription,
@ -257,7 +257,7 @@ var CmdLabelDelete = cli.Command{
func runLabelDelete(ctx *cli.Context) error { func runLabelDelete(ctx *cli.Context) error {
login, owner, repo := initCommand() login, owner, repo := initCommand()
err := login.Client().DeleteLabel(owner, repo, ctx.Int64("id")) _, err := login.Client().DeleteLabel(owner, repo, ctx.Int64("id"))
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@ -187,22 +187,25 @@ func runLoginAddMain(name, token, user, passwd, sshKey, giteaURL string, insecur
log.Fatal("Unable to load config file " + yamlConfigPath) log.Fatal("Unable to load config file " + yamlConfigPath)
} }
client := gitea.NewClient(giteaURL, token) httpClient := &http.Client{}
if len(token) == 0 {
client.SetBasicAuth(user, passwd)
}
if insecure { if insecure {
cookieJar, _ := cookiejar.New(nil) cookieJar, _ := cookiejar.New(nil)
httpClient = &http.Client{
client.SetHTTPClient(&http.Client{
Jar: cookieJar, Jar: cookieJar,
Transport: &http.Transport{ Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}, }}
}) }
client, err := gitea.NewClient(giteaURL,
gitea.SetToken(token),
gitea.SetBasicAuth(user, passwd),
gitea.SetHTTPClient(httpClient),
)
if err != nil {
log.Fatal(err)
} }
u, err := client.GetMyUserInfo() u, _, err := client.GetMyUserInfo()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -210,7 +213,7 @@ func runLoginAddMain(name, token, user, passwd, sshKey, giteaURL string, insecur
if len(token) == 0 { if len(token) == 0 {
// create token // create token
host, _ := os.Hostname() host, _ := os.Hostname()
tl, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{}) tl, _, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{})
if err != nil { if err != nil {
return err return err
} }
@ -221,7 +224,7 @@ func runLoginAddMain(name, token, user, passwd, sshKey, giteaURL string, insecur
break break
} }
} }
t, err := client.CreateAccessToken(gitea.CreateAccessTokenOption{Name: tokenName}) t, _, err := client.CreateAccessToken(gitea.CreateAccessTokenOption{Name: tokenName})
if err != nil { if err != nil {
return err return err
} }

View File

@ -24,13 +24,16 @@ var CmdNotifications = cli.Command{
Aliases: []string{"a"}, Aliases: []string{"a"},
Usage: "show all notifications of related gitea instance", Usage: "show all notifications of related gitea instance",
}, },
/* // not supported jet
&cli.BoolFlag{ &cli.BoolFlag{
Name: "read", Name: "read",
Aliases: []string{"rd"}, Aliases: []string{"rd"},
Usage: "show read notifications instead unread", Usage: "show read notifications instead unread",
}, },
*/ &cli.BoolFlag{
Name: "pinned",
Aliases: []string{"pd"},
Usage: "show pinned notifications instead unread",
},
&cli.IntFlag{ &cli.IntFlag{
Name: "page", Name: "page",
Aliases: []string{"p"}, Aliases: []string{"p"},
@ -54,15 +57,25 @@ func runNotifications(ctx *cli.Context) error {
PageSize: ctx.Int("limit"), PageSize: ctx.Int("limit"),
} }
var status []gitea.NotifyStatus
if ctx.Bool("read") {
status = []gitea.NotifyStatus{gitea.NotifyStatusRead}
}
if ctx.Bool("pinned") {
status = append(status, gitea.NotifyStatusPinned)
}
if ctx.Bool("all") { if ctx.Bool("all") {
login := initCommandLoginOnly() login := initCommandLoginOnly()
news, err = login.Client().ListNotifications(gitea.ListNotificationOptions{ news, _, err = login.Client().ListNotifications(gitea.ListNotificationOptions{
ListOptions: listOpts, ListOptions: listOpts,
Status: status,
}) })
} else { } else {
login, owner, repo := initCommand() login, owner, repo := initCommand()
news, err = login.Client().ListRepoNotifications(owner, repo, gitea.ListNotificationOptions{ news, _, err = login.Client().ListRepoNotifications(owner, repo, gitea.ListNotificationOptions{
ListOptions: listOpts, ListOptions: listOpts,
Status: status,
}) })
} }
if err != nil { if err != nil {

View File

@ -52,7 +52,7 @@ func runPulls(ctx *cli.Context) error {
state = gitea.StateClosed state = gitea.StateClosed
} }
prs, err := login.Client().ListRepoPullRequests(owner, repo, gitea.ListPullRequestsOptions{ prs, _, err := login.Client().ListRepoPullRequests(owner, repo, gitea.ListPullRequestsOptions{
State: state, State: state,
}) })
@ -120,7 +120,7 @@ func runPullsCheckout(ctx *cli.Context) error {
if err != nil { if err != nil {
return err return err
} }
pr, err := login.Client().GetPullRequest(owner, repo, idx) pr, _, err := login.Client().GetPullRequest(owner, repo, idx)
if err != nil { if err != nil {
return err return err
} }
@ -204,7 +204,7 @@ func runPullsClean(ctx *cli.Context) error {
if err != nil { if err != nil {
return err return err
} }
pr, err := login.Client().GetPullRequest(owner, repo, idx) pr, _, err := login.Client().GetPullRequest(owner, repo, idx)
if err != nil { if err != nil {
return err return err
} }
@ -298,7 +298,7 @@ func runPullsCreate(ctx *cli.Context) error {
login, ownerArg, repoArg := initCommand() login, ownerArg, repoArg := initCommand()
client := login.Client() client := login.Client()
repo, err := login.Client().GetRepo(ownerArg, repoArg) repo, _, err := login.Client().GetRepo(ownerArg, repoArg)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -347,7 +347,7 @@ func runPullsCreate(ctx *cli.Context) error {
fmt.Printf("Error occurred during 'git push':\n%s\n", err.Error()) fmt.Printf("Error occurred during 'git push':\n%s\n", err.Error())
} }
pr, err := client.CreatePullRequest(ownerArg, repoArg, gitea.CreatePullRequestOption{ pr, _, err := client.CreatePullRequest(ownerArg, repoArg, gitea.CreatePullRequestOption{
Head: head, Head: head,
Base: base, Base: base,
Title: title, Title: title,

View File

@ -29,7 +29,7 @@ var CmdReleases = cli.Command{
func runReleases(ctx *cli.Context) error { func runReleases(ctx *cli.Context) error {
login, owner, repo := initCommand() login, owner, repo := initCommand()
releases, err := login.Client().ListReleases(owner, repo, gitea.ListReleasesOptions{}) releases, _, err := login.Client().ListReleases(owner, repo, gitea.ListReleasesOptions{})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -110,7 +110,7 @@ var CmdReleaseCreate = cli.Command{
func runReleaseCreate(ctx *cli.Context) error { func runReleaseCreate(ctx *cli.Context) error {
login, owner, repo := initCommand() login, owner, repo := initCommand()
release, err := login.Client().CreateRelease(owner, repo, gitea.CreateReleaseOption{ release, _, err := login.Client().CreateRelease(owner, repo, gitea.CreateReleaseOption{
TagName: ctx.String("tag"), TagName: ctx.String("tag"),
Target: ctx.String("target"), Target: ctx.String("target"),
Title: ctx.String("title"), Title: ctx.String("title"),
@ -136,7 +136,7 @@ func runReleaseCreate(ctx *cli.Context) error {
filePath := filepath.Base(asset) filePath := filepath.Base(asset)
if _, err = login.Client().CreateReleaseAttachment(owner, repo, release.ID, file, filePath); err != nil { if _, _, err = login.Client().CreateReleaseAttachment(owner, repo, release.ID, file, filePath); err != nil {
file.Close() file.Close()
log.Fatal(err) log.Fatal(err)
} }

View File

@ -58,11 +58,11 @@ func runReposList(ctx *cli.Context) error {
var err error var err error
if org != "" { if org != "" {
rps, err = login.Client().ListOrgRepos(org, gitea.ListOrgReposOptions{}) rps, _, err = login.Client().ListOrgRepos(org, gitea.ListOrgReposOptions{})
} else if user != "" { } else if user != "" {
rps, err = login.Client().ListUserRepos(user, gitea.ListReposOptions{}) rps, _, err = login.Client().ListUserRepos(user, gitea.ListReposOptions{})
} else { } else {
rps, err = login.Client().ListMyRepos(gitea.ListReposOptions{}) rps, _, err = login.Client().ListMyRepos(gitea.ListReposOptions{})
} }
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View File

@ -66,17 +66,17 @@ func runTrackedTimes(ctx *cli.Context) error {
fmt.Println(ctx.Command.ArgsUsage) fmt.Println(ctx.Command.ArgsUsage)
if user == "" { if user == "" {
// get all tracked times on the repo // get all tracked times on the repo
times, err = client.GetRepoTrackedTimes(owner, repo) times, _, err = client.GetRepoTrackedTimes(owner, repo)
} else if strings.HasPrefix(user, "#") { } else if strings.HasPrefix(user, "#") {
// get all tracked times on the specified issue // get all tracked times on the specified issue
issue, err := argToIndex(user) issue, err := argToIndex(user)
if err != nil { if err != nil {
return err return err
} }
times, err = client.ListTrackedTimes(owner, repo, issue, gitea.ListTrackedTimesOptions{}) times, _, err = client.ListTrackedTimes(owner, repo, issue, gitea.ListTrackedTimesOptions{})
} else { } else {
// get all tracked times by the specified user // get all tracked times by the specified user
times, err = client.GetUserTrackedTimes(owner, repo, user) times, _, err = client.GetUserTrackedTimes(owner, repo, user)
} }
if err != nil { if err != nil {
@ -185,7 +185,7 @@ func runTrackedTimesAdd(ctx *cli.Context) error {
log.Fatal(err) log.Fatal(err)
} }
_, err = login.Client().AddTime(owner, repo, issue, gitea.AddTimeOption{ _, _, err = login.Client().AddTime(owner, repo, issue, gitea.AddTimeOption{
Time: int64(duration.Seconds()), Time: int64(duration.Seconds()),
}) })
if err != nil { if err != nil {
@ -227,7 +227,7 @@ func runTrackedTimesDelete(ctx *cli.Context) error {
log.Fatal(err) log.Fatal(err)
} }
err = client.DeleteTime(owner, repo, issue, timeID) _, err = client.DeleteTime(owner, repo, issue, timeID)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -262,7 +262,7 @@ func runTrackedTimesReset(ctx *cli.Context) error {
log.Fatal(err) log.Fatal(err)
} }
err = client.ResetIssueTime(owner, repo, issue) _, err = client.ResetIssueTime(owner, repo, issue)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

2
go.mod
View File

@ -4,7 +4,7 @@ go 1.12
require ( require (
code.gitea.io/gitea-vet v0.2.0 code.gitea.io/gitea-vet v0.2.0
code.gitea.io/sdk/gitea v0.12.1 code.gitea.io/sdk/gitea v0.13.0
github.com/araddon/dateparse v0.0.0-20200409225146-d820a6159ab1 github.com/araddon/dateparse v0.0.0-20200409225146-d820a6159ab1
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
github.com/go-git/go-git/v5 v5.1.0 github.com/go-git/go-git/v5 v5.1.0

4
go.sum
View File

@ -1,7 +1,7 @@
code.gitea.io/gitea-vet v0.2.0 h1:xkUePzbHI8e0qp4Aly4GBSd0+6cqEMVTrdZq57fPozo= code.gitea.io/gitea-vet v0.2.0 h1:xkUePzbHI8e0qp4Aly4GBSd0+6cqEMVTrdZq57fPozo=
code.gitea.io/gitea-vet v0.2.0/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= code.gitea.io/gitea-vet v0.2.0/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE=
code.gitea.io/sdk/gitea v0.12.1 h1:bMgjEqPnNX/i6TpVwXwpjJtFOnUSuC9P6yy/jjy8sjY= code.gitea.io/sdk/gitea v0.13.0 h1:iHognp8ZMhMFLooUUNZFpm8IHaC9qoHJDvAE5vTm5aw=
code.gitea.io/sdk/gitea v0.12.1/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= code.gitea.io/sdk/gitea v0.13.0/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs=

44
vendor/code.gitea.io/sdk/gitea/admin_cron.go generated vendored Normal file
View File

@ -0,0 +1,44 @@
// 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"
"time"
)
// CronTask represents a Cron task
type CronTask struct {
Name string `json:"name"`
Schedule string `json:"schedule"`
Next time.Time `json:"next"`
Prev time.Time `json:"prev"`
ExecTimes int64 `json:"exec_times"`
}
// ListCronTaskOptions list options for ListCronTasks
type ListCronTaskOptions struct {
ListOptions
}
// ListCronTasks list available cron tasks
func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
opt.setDefaults()
ct := make([]*CronTask, 0, opt.PageSize)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/cron?%s", opt.getURLQuery().Encode()), jsonHeader, nil, &ct)
return ct, resp, err
}
// RunCronTasks run a cron task
func (c *Client) RunCronTasks(task string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, err
}
_, resp, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil)
return resp, err
}

View File

@ -17,19 +17,20 @@ type AdminListOrgsOptions struct {
} }
// AdminListOrgs lists all orgs // AdminListOrgs lists all orgs
func (c *Client) AdminListOrgs(opt AdminListOrgsOptions) ([]*Organization, error) { func (c *Client) AdminListOrgs(opt AdminListOrgsOptions) ([]*Organization, *Response, error) {
opt.setDefaults() opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize) orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/admin/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs)
return orgs, resp, err
} }
// AdminCreateOrg create an organization // AdminCreateOrg create an organization
func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) { func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
org := new(Organization) org := new(Organization)
return org, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user), resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user), jsonHeader, bytes.NewReader(body), org)
jsonHeader, bytes.NewReader(body), org) return org, resp, err
} }

View File

@ -11,12 +11,12 @@ import (
) )
// AdminCreateRepo create a repo // AdminCreateRepo create a repo
func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, error) { func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user), resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user), jsonHeader, bytes.NewReader(body), repo)
jsonHeader, bytes.NewReader(body), repo) return repo, resp, err
} }

View File

@ -17,10 +17,11 @@ type AdminListUsersOptions struct {
} }
// AdminListUsers lists all users // AdminListUsers lists all users
func (c *Client) AdminListUsers(opt AdminListUsersOptions) ([]*User, error) { func (c *Client) AdminListUsers(opt AdminListUsersOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/admin/users?%s", opt.getURLQuery().Encode()), nil, nil, &users) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/users?%s", opt.getURLQuery().Encode()), nil, nil, &users)
return users, resp, err
} }
// CreateUserOption create user options // CreateUserOption create user options
@ -35,14 +36,29 @@ type CreateUserOption struct {
SendNotify bool `json:"send_notify"` SendNotify bool `json:"send_notify"`
} }
// Validate the CreateUserOption struct
func (opt CreateUserOption) Validate() error {
if len(opt.Email) == 0 {
return fmt.Errorf("email is empty")
}
if len(opt.Username) == 0 {
return fmt.Errorf("username is empty")
}
return nil
}
// AdminCreateUser create a user // AdminCreateUser create a user
func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, error) { func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
user := new(User) user := new(User)
return user, c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user) resp, err := c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user)
return user, resp, err
} }
// EditUserOption edit user options // EditUserOption edit user options
@ -65,33 +81,34 @@ type EditUserOption struct {
} }
// AdminEditUser modify user informations // AdminEditUser modify user informations
func (c *Client) AdminEditUser(user string, opt EditUserOption) error { func (c *Client) AdminEditUser(user string, opt EditUserOption) (*Response, error) {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
_, err = c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body))
return err
}
// AdminDeleteUser delete one user according name
func (c *Client) AdminDeleteUser(user string) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil)
return err
}
// AdminCreateUserPublicKey adds a public key for the user
func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, resp, err := c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body))
return resp, err
}
// AdminDeleteUser delete one user according name
func (c *Client) AdminDeleteUser(user string) (*Response, error) {
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil)
return resp, err
}
// AdminCreateUserPublicKey adds a public key for the user
func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, *Response, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, nil, err
}
key := new(PublicKey) key := new(PublicKey)
return key, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key)
return key, resp, err
} }
// AdminDeleteUserPublicKey deletes a user's public key // AdminDeleteUserPublicKey deletes a user's public key
func (c *Client) AdminDeleteUserPublicKey(user string, keyID int) error { func (c *Client) AdminDeleteUserPublicKey(user string, keyID int) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s/keys/%d", user, keyID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s/keys/%d", user, keyID), nil, nil)
return err return resp, err
} }

View File

@ -30,47 +30,47 @@ type ListReleaseAttachmentsOptions struct {
} }
// ListReleaseAttachments list release's attachments // ListReleaseAttachments list release's attachments
func (c *Client) ListReleaseAttachments(user, repo string, release int64, opt ListReleaseAttachmentsOptions) ([]*Attachment, error) { func (c *Client) ListReleaseAttachments(user, repo string, release int64, opt ListReleaseAttachmentsOptions) ([]*Attachment, *Response, error) {
opt.setDefaults() opt.setDefaults()
attachments := make([]*Attachment, 0, opt.PageSize) attachments := make([]*Attachment, 0, opt.PageSize)
err := c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases/%d/assets?%s", user, repo, release, opt.getURLQuery().Encode()), fmt.Sprintf("/repos/%s/%s/releases/%d/assets?%s", user, repo, release, opt.getURLQuery().Encode()),
nil, nil, &attachments) nil, nil, &attachments)
return attachments, err return attachments, resp, err
} }
// GetReleaseAttachment returns the requested attachment // GetReleaseAttachment returns the requested attachment
func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, error) { func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, *Response, error) {
a := new(Attachment) a := new(Attachment)
err := c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id),
nil, nil, &a) nil, nil, &a)
return a, err return a, resp, err
} }
// CreateReleaseAttachment creates an attachment for the given release // CreateReleaseAttachment creates an attachment for the given release
func (c *Client) CreateReleaseAttachment(user, repo string, release int64, file io.Reader, filename string) (*Attachment, error) { func (c *Client) CreateReleaseAttachment(user, repo string, release int64, file io.Reader, filename string) (*Attachment, *Response, error) {
// Write file to body // Write file to body
body := new(bytes.Buffer) body := new(bytes.Buffer)
writer := multipart.NewWriter(body) writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("attachment", filename) part, err := writer.CreateFormFile("attachment", filename)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
if _, err = io.Copy(part, file); err != nil { if _, err = io.Copy(part, file); err != nil {
return nil, err return nil, nil, err
} }
if err = writer.Close(); err != nil { if err = writer.Close(); err != nil {
return nil, err return nil, nil, err
} }
// Send request // Send request
attachment := new(Attachment) attachment := new(Attachment)
err = c.getParsedResponse("POST", resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release),
http.Header{"Content-Type": {writer.FormDataContentType()}}, body, &attachment) http.Header{"Content-Type": {writer.FormDataContentType()}}, body, &attachment)
return attachment, err return attachment, resp, err
} }
// EditAttachmentOptions options for editing attachments // EditAttachmentOptions options for editing attachments
@ -79,17 +79,18 @@ type EditAttachmentOptions struct {
} }
// EditReleaseAttachment updates the given attachment with the given options // EditReleaseAttachment updates the given attachment with the given options
func (c *Client) EditReleaseAttachment(user, repo string, release int64, attachment int64, form EditAttachmentOptions) (*Attachment, error) { func (c *Client) EditReleaseAttachment(user, repo string, release int64, attachment int64, form EditAttachmentOptions) (*Attachment, *Response, error) {
body, err := json.Marshal(&form) body, err := json.Marshal(&form)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
attach := new(Attachment) attach := new(Attachment)
return attach, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, attachment), jsonHeader, bytes.NewReader(body), attach) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, attachment), jsonHeader, bytes.NewReader(body), attach)
return attach, resp, err
} }
// DeleteReleaseAttachment deletes the given attachment including the uploaded file // DeleteReleaseAttachment deletes the given attachment including the uploaded file
func (c *Client) DeleteReleaseAttachment(user, repo string, release int64, id int64) error { func (c *Client) DeleteReleaseAttachment(user, repo string, release int64, id int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil)
return err return resp, err
} }

View File

@ -6,6 +6,7 @@
package gitea package gitea
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -22,7 +23,7 @@ var jsonHeader = http.Header{"content-type": []string{"application/json"}}
// Version return the library version // Version return the library version
func Version() string { func Version() string {
return "0.12.0" return "0.13.0"
} }
// Client represents a Gitea API client. // Client represents a Gitea API client.
@ -34,48 +35,123 @@ type Client struct {
otp string otp string
sudo string sudo string
client *http.Client client *http.Client
ctx context.Context
serverVersion *version.Version serverVersion *version.Version
versionLock sync.RWMutex versionLock sync.RWMutex
} }
// Response represents the gitea response
type Response struct {
*http.Response
}
// NewClient initializes and returns a API client. // NewClient initializes and returns a API client.
func NewClient(url, token string) *Client { func NewClient(url string, options ...func(*Client)) (*Client, error) {
return &Client{ client := &Client{
url: strings.TrimSuffix(url, "/"), url: strings.TrimSuffix(url, "/"),
accessToken: token,
client: &http.Client{}, client: &http.Client{},
ctx: context.Background(),
} }
for _, opt := range options {
opt(client)
}
if err := client.CheckServerVersionConstraint(">=1.10"); err != nil {
return nil, err
}
return client, nil
} }
// NewClientWithHTTP creates an API client with a custom http client // NewClientWithHTTP creates an API client with a custom http client
// Deprecated use SetHTTPClient option
func NewClientWithHTTP(url string, httpClient *http.Client) *Client { func NewClientWithHTTP(url string, httpClient *http.Client) *Client {
client := NewClient(url, "") client, _ := NewClient(url, SetHTTPClient(httpClient))
client.client = httpClient
return client return client
} }
// SetBasicAuth sets basicauth // SetHTTPClient is an option for NewClient to set custom http client
func SetHTTPClient(httpClient *http.Client) func(client *Client) {
return func(client *Client) {
client.client = httpClient
}
}
// SetToken is an option for NewClient to set token
func SetToken(token string) func(client *Client) {
return func(client *Client) {
client.accessToken = token
}
}
// SetBasicAuth is an option for NewClient to set username and password
func SetBasicAuth(username, password string) func(client *Client) {
return func(client *Client) {
client.SetBasicAuth(username, password)
}
}
// SetBasicAuth sets username and password
func (c *Client) SetBasicAuth(username, password string) { func (c *Client) SetBasicAuth(username, password string) {
c.username, c.password = username, password c.username, c.password = username, password
} }
// SetOTP is an option for NewClient to set OTP for 2FA
func SetOTP(otp string) func(client *Client) {
return func(client *Client) {
client.SetOTP(otp)
}
}
// SetOTP sets OTP for 2FA // SetOTP sets OTP for 2FA
func (c *Client) SetOTP(otp string) { func (c *Client) SetOTP(otp string) {
c.otp = otp c.otp = otp
} }
// SetContext is an option for NewClient to set context
func SetContext(ctx context.Context) func(client *Client) {
return func(client *Client) {
client.SetContext(ctx)
}
}
// SetContext set context witch is used for http requests
func (c *Client) SetContext(ctx context.Context) {
c.ctx = ctx
}
// SetHTTPClient replaces default http.Client with user given one. // SetHTTPClient replaces default http.Client with user given one.
func (c *Client) SetHTTPClient(client *http.Client) { func (c *Client) SetHTTPClient(client *http.Client) {
c.client = client c.client = client
} }
// SetSudo is an option for NewClient to set sudo header
func SetSudo(sudo string) func(client *Client) {
return func(client *Client) {
client.SetSudo(sudo)
}
}
// SetSudo sets username to impersonate. // SetSudo sets username to impersonate.
func (c *Client) SetSudo(sudo string) { func (c *Client) SetSudo(sudo string) {
c.sudo = sudo c.sudo = sudo
} }
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) { func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) {
req, err := http.NewRequest(method, c.url+"/api/v1"+path, body) req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body)
if err != nil {
return nil, nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
return data, &Response{resp}, nil
}
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) {
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
} }
@ -95,30 +171,34 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read
req.Header[k] = v req.Header[k] = v
} }
return c.client.Do(req) resp, err := c.client.Do(req)
}
func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) {
resp, err := c.doRequest(method, path, header, body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Response{resp}, nil
}
func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, *Response, error) {
resp, err := c.doRequest(method, path, header, body)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close() defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) data, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, resp, err
} }
switch resp.StatusCode { switch resp.StatusCode {
case 403: case 403:
return nil, errors.New("403 Forbidden") return data, resp, errors.New("403 Forbidden")
case 404: case 404:
return nil, errors.New("404 Not Found") return data, resp, errors.New("404 Not Found")
case 409: case 409:
return nil, errors.New("409 Conflict") return data, resp, errors.New("409 Conflict")
case 422: case 422:
return nil, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) return data, resp, fmt.Errorf("422 Unprocessable Entity: %s", string(data))
} }
if resp.StatusCode/100 != 2 { if resp.StatusCode/100 != 2 {
@ -126,28 +206,28 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re
if err = json.Unmarshal(data, &errMap); err != nil { if err = json.Unmarshal(data, &errMap); err != nil {
// when the JSON can't be parsed, data was probably empty or a plain string, // when the JSON can't be parsed, data was probably empty or a plain string,
// so we try to return a helpful error anyway // so we try to return a helpful error anyway
return nil, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data)) return data, resp, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data))
} }
return nil, errors.New(errMap["message"].(string)) return data, resp, errors.New(errMap["message"].(string))
} }
return data, nil return data, resp, nil
} }
func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error { func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) (*Response, error) {
data, err := c.getResponse(method, path, header, body) data, resp, err := c.getResponse(method, path, header, body)
if err != nil { if err != nil {
return err return nil, err
} }
return json.Unmarshal(data, obj) return resp, json.Unmarshal(data, obj)
} }
func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, error) { func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, *Response, error) {
resp, err := c.doRequest(method, path, header, body) resp, err := c.doRequest(method, path, header, body)
if err != nil { if err != nil {
return -1, err return -1, resp, err
} }
defer resp.Body.Close() defer resp.Body.Close()
return resp.StatusCode, nil return resp.StatusCode, resp, nil
} }

View File

@ -16,12 +16,13 @@ type ListForksOptions struct {
} }
// ListForks list a repository's forks // ListForks list a repository's forks
func (c *Client) ListForks(user string, repo string, opt ListForksOptions) ([]*Repository, error) { func (c *Client) ListForks(user string, repo string, opt ListForksOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
forks := make([]*Repository, opt.PageSize) forks := make([]*Repository, opt.PageSize)
return forks, c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/forks?%s", user, repo, opt.getURLQuery().Encode()), fmt.Sprintf("/repos/%s/%s/forks?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &forks) nil, nil, &forks)
return forks, resp, err
} }
// CreateForkOption options for creating a fork // CreateForkOption options for creating a fork
@ -31,11 +32,12 @@ type CreateForkOption struct {
} }
// CreateFork create a fork of a repository // CreateFork create a fork of a repository
func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Repository, error) { func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Repository, *Response, error) {
body, err := json.Marshal(form) body, err := json.Marshal(form)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
fork := new(Repository) fork := new(Repository)
return fork, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork)
return fork, resp, err
} }

View File

@ -18,7 +18,8 @@ type GitBlobResponse struct {
} }
// GetBlob get the blob of a repository file // GetBlob get the blob of a repository file
func (c *Client) GetBlob(user, repo, sha string) (*GitBlobResponse, error) { func (c *Client) GetBlob(user, repo, sha string) (*GitBlobResponse, *Response, error) {
blob := new(GitBlobResponse) blob := new(GitBlobResponse)
return blob, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/blobs/%s", user, repo, sha), nil, nil, blob) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/blobs/%s", user, repo, sha), nil, nil, blob)
return blob, resp, err
} }

View File

@ -23,16 +23,18 @@ type ListRepoGitHooksOptions struct {
} }
// ListRepoGitHooks list all the Git hooks of one repository // ListRepoGitHooks list all the Git hooks of one repository
func (c *Client) ListRepoGitHooks(user, repo string, opt ListRepoGitHooksOptions) ([]*GitHook, error) { func (c *Client) ListRepoGitHooks(user, repo string, opt ListRepoGitHooksOptions) ([]*GitHook, *Response, error) {
opt.setDefaults() opt.setDefaults()
hooks := make([]*GitHook, 0, opt.PageSize) hooks := make([]*GitHook, 0, opt.PageSize)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks)
return hooks, resp, err
} }
// GetRepoGitHook get a Git hook of a repository // GetRepoGitHook get a Git hook of a repository
func (c *Client) GetRepoGitHook(user, repo, id string) (*GitHook, error) { func (c *Client) GetRepoGitHook(user, repo, id string) (*GitHook, *Response, error) {
h := new(GitHook) h := new(GitHook)
return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil, h) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil, h)
return h, resp, err
} }
// EditGitHookOption options when modifying one Git hook // EditGitHookOption options when modifying one Git hook
@ -41,17 +43,17 @@ type EditGitHookOption struct {
} }
// EditRepoGitHook modify one Git hook of a repository // EditRepoGitHook modify one Git hook of a repository
func (c *Client) EditRepoGitHook(user, repo, id string, opt EditGitHookOption) error { func (c *Client) EditRepoGitHook(user, repo, id string, opt EditGitHookOption) (*Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// DeleteRepoGitHook delete one Git hook from a repository // DeleteRepoGitHook delete one Git hook from a repository
func (c *Client) DeleteRepoGitHook(user, repo, id string) error { func (c *Client) DeleteRepoGitHook(user, repo, id string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil)
return err return resp, err
} }

View File

@ -30,29 +30,33 @@ type ListHooksOptions struct {
} }
// ListOrgHooks list all the hooks of one organization // ListOrgHooks list all the hooks of one organization
func (c *Client) ListOrgHooks(org string, opt ListHooksOptions) ([]*Hook, error) { func (c *Client) ListOrgHooks(org string, opt ListHooksOptions) ([]*Hook, *Response, error) {
opt.setDefaults() opt.setDefaults()
hooks := make([]*Hook, 0, opt.PageSize) hooks := make([]*Hook, 0, opt.PageSize)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks?%s", org, opt.getURLQuery().Encode()), nil, nil, &hooks) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks?%s", org, opt.getURLQuery().Encode()), nil, nil, &hooks)
return hooks, resp, err
} }
// ListRepoHooks list all the hooks of one repository // ListRepoHooks list all the hooks of one repository
func (c *Client) ListRepoHooks(user, repo string, opt ListHooksOptions) ([]*Hook, error) { func (c *Client) ListRepoHooks(user, repo string, opt ListHooksOptions) ([]*Hook, *Response, error) {
opt.setDefaults() opt.setDefaults()
hooks := make([]*Hook, 0, opt.PageSize) hooks := make([]*Hook, 0, opt.PageSize)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks)
return hooks, resp, err
} }
// GetOrgHook get a hook of an organization // GetOrgHook get a hook of an organization
func (c *Client) GetOrgHook(org string, id int64) (*Hook, error) { func (c *Client) GetOrgHook(org string, id int64) (*Hook, *Response, error) {
h := new(Hook) h := new(Hook)
return h, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil, h) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil, h)
return h, resp, err
} }
// GetRepoHook get a hook of a repository // GetRepoHook get a hook of a repository
func (c *Client) GetRepoHook(user, repo string, id int64) (*Hook, error) { func (c *Client) GetRepoHook(user, repo string, id int64) (*Hook, *Response, error) {
h := new(Hook) h := new(Hook)
return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil, h) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil, h)
return h, resp, err
} }
// CreateHookOption options when create a hook // CreateHookOption options when create a hook
@ -64,24 +68,37 @@ type CreateHookOption struct {
Active bool `json:"active"` Active bool `json:"active"`
} }
// Validate the CreateHookOption struct
func (opt CreateHookOption) Validate() error {
if len(opt.Type) == 0 {
return fmt.Errorf("hook type needed")
}
return nil
}
// CreateOrgHook create one hook for an organization, with options // CreateOrgHook create one hook for an organization, with options
func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, error) { func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
h := new(Hook) h := new(Hook)
return h, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/hooks", org), jsonHeader, bytes.NewReader(body), h) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/hooks", org), jsonHeader, bytes.NewReader(body), h)
return h, resp, err
} }
// CreateRepoHook create one hook for a repository, with options // CreateRepoHook create one hook for a repository, with options
func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, error) { func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
h := new(Hook) h := new(Hook)
return h, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h)
return h, resp, err
} }
// EditHookOption options when modify one hook // EditHookOption options when modify one hook
@ -93,33 +110,33 @@ type EditHookOption struct {
} }
// EditOrgHook modify one hook of an organization, with hook id and options // EditOrgHook modify one hook of an organization, with hook id and options
func (c *Client) EditOrgHook(org string, id int64, opt EditHookOption) error { func (c *Client) EditOrgHook(org string, id int64, opt EditHookOption) (*Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// EditRepoHook modify one hook of a repository, with hook id and options // EditRepoHook modify one hook of a repository, with hook id and options
func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) error { func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) (*Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// DeleteOrgHook delete one hook from an organization, with hook id // DeleteOrgHook delete one hook from an organization, with hook id
func (c *Client) DeleteOrgHook(org string, id int64) error { func (c *Client) DeleteOrgHook(org string, id int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil)
return err return resp, err
} }
// DeleteRepoHook delete one hook from a repository, with hook id // DeleteRepoHook delete one hook from a repository, with hook id
func (c *Client) DeleteRepoHook(user, repo string, id int64) error { func (c *Client) DeleteRepoHook(user, repo string, id int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil)
return err return resp, err
} }

View File

@ -44,6 +44,7 @@ type Issue struct {
Assignees []*User `json:"assignees"` Assignees []*User `json:"assignees"`
// Whether the issue is open or closed // Whether the issue is open or closed
State StateType `json:"state"` State StateType `json:"state"`
IsLocked bool `json:"is_locked"`
Comments int `json:"comments"` Comments int `json:"comments"`
Created time.Time `json:"created_at"` Created time.Time `json:"created_at"`
Updated time.Time `json:"updated_at"` Updated time.Time `json:"updated_at"`
@ -113,13 +114,13 @@ func (opt *ListIssueOption) QueryEncode() string {
} }
// ListIssues returns all issues assigned the authenticated user // ListIssues returns all issues assigned the authenticated user
func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, *Response, error) {
opt.setDefaults() opt.setDefaults()
issues := make([]*Issue, 0, opt.PageSize) issues := make([]*Issue, 0, opt.PageSize)
link, _ := url.Parse("/repos/issues/search") link, _ := url.Parse("/repos/issues/search")
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
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.CheckServerVersionConstraint(">=1.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 {
@ -127,17 +128,17 @@ func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) {
} }
} }
} }
return issues, err return issues, resp, err
} }
// ListRepoIssues returns all issues for a given repository // ListRepoIssues returns all issues for a given repository
func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) { func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, *Response, error) {
opt.setDefaults() opt.setDefaults()
issues := make([]*Issue, 0, opt.PageSize) issues := make([]*Issue, 0, opt.PageSize)
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()
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.CheckServerVersionConstraint(">=1.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 {
@ -145,17 +146,17 @@ func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Iss
} }
} }
} }
return issues, err return issues, resp, err
} }
// GetIssue returns a single issue for a given repository // GetIssue returns a single issue for a given repository
func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, *Response, error) {
issue := new(Issue) issue := new(Issue)
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.CheckServerVersionConstraint(">=1.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, err return issue, resp, err
} }
// CreateIssueOption options to create one issue // CreateIssueOption options to create one issue
@ -173,15 +174,27 @@ type CreateIssueOption struct {
Closed bool `json:"closed"` Closed bool `json:"closed"`
} }
// Validate the CreateIssueOption struct
func (opt CreateIssueOption) Validate() error {
if len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
return nil
}
// CreateIssue create a new issue for a given repository // CreateIssue create a new issue for a given repository
func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) { func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
issue := new(Issue) issue := new(Issue)
return issue, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo), resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo),
jsonHeader, bytes.NewReader(body), issue) jsonHeader, bytes.NewReader(body), issue)
return issue, resp, err
} }
// EditIssueOption options for editing an issue // EditIssueOption options for editing an issue
@ -195,13 +208,26 @@ type EditIssueOption struct {
Deadline *time.Time `json:"due_date"` Deadline *time.Time `json:"due_date"`
} }
// Validate the EditIssueOption struct
func (opt EditIssueOption) Validate() error {
if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
return nil
}
// EditIssue modify an existing issue for a given repository // EditIssue modify an existing issue for a given repository
func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, error) { func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
issue := new(Issue) issue := new(Issue)
return issue, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), resp, err := c.getParsedResponse("PATCH",
fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index),
jsonHeader, bytes.NewReader(body), issue) jsonHeader, bytes.NewReader(body), issue)
return issue, resp, err
} }

View File

@ -46,30 +46,33 @@ func (opt *ListIssueCommentOptions) QueryEncode() string {
} }
// ListIssueComments list comments on an issue. // ListIssueComments list comments on an issue.
func (c *Client) ListIssueComments(owner, repo string, index int64, opt ListIssueCommentOptions) ([]*Comment, error) { func (c *Client) ListIssueComments(owner, repo string, index int64, opt ListIssueCommentOptions) ([]*Comment, *Response, error) {
opt.setDefaults() opt.setDefaults()
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
comments := make([]*Comment, 0, opt.PageSize) comments := make([]*Comment, 0, opt.PageSize)
return comments, c.getParsedResponse("GET", link.String(), nil, nil, &comments) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &comments)
return comments, resp, err
} }
// ListRepoIssueComments list comments for a given repo. // ListRepoIssueComments list comments for a given repo.
func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentOptions) ([]*Comment, error) { func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentOptions) ([]*Comment, *Response, error) {
opt.setDefaults() opt.setDefaults()
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
comments := make([]*Comment, 0, opt.PageSize) comments := make([]*Comment, 0, opt.PageSize)
return comments, c.getParsedResponse("GET", link.String(), nil, nil, &comments) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &comments)
return comments, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return comment, err return comment, nil, err
} }
return comment, 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)
return comment, resp, err
} }
// CreateIssueCommentOption options for creating a comment on an issue // CreateIssueCommentOption options for creating a comment on an issue
@ -77,14 +80,26 @@ type CreateIssueCommentOption struct {
Body string `json:"body"` Body string `json:"body"`
} }
// Validate the CreateIssueCommentOption struct
func (opt CreateIssueCommentOption) Validate() error {
if len(opt.Body) == 0 {
return fmt.Errorf("body is empty")
}
return nil
}
// CreateIssueComment create comment on an issue. // CreateIssueComment create comment on an issue.
func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, error) { func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
comment := new(Comment) comment := new(Comment)
return comment, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), jsonHeader, bytes.NewReader(body), comment) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), jsonHeader, bytes.NewReader(body), comment)
return comment, resp, err
} }
// EditIssueCommentOption options for editing a comment // EditIssueCommentOption options for editing a comment
@ -92,18 +107,30 @@ type EditIssueCommentOption struct {
Body string `json:"body"` Body string `json:"body"`
} }
// Validate the EditIssueCommentOption struct
func (opt EditIssueCommentOption) Validate() error {
if len(opt.Body) == 0 {
return fmt.Errorf("body is empty")
}
return nil
}
// EditIssueComment edits an issue comment. // EditIssueComment edits an issue comment.
func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, error) { func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
comment := new(Comment) comment := new(Comment)
return comment, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), jsonHeader, bytes.NewReader(body), comment) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), jsonHeader, bytes.NewReader(body), comment)
return comment, resp, err
} }
// DeleteIssueComment deletes an issue comment. // DeleteIssueComment deletes an issue comment.
func (c *Client) DeleteIssueComment(owner, repo string, commentID int64) error { func (c *Client) DeleteIssueComment(owner, repo string, commentID int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), nil, nil)
return err return resp, err
} }

View File

@ -8,6 +8,8 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"regexp"
"strings"
) )
// Label a label to an issue or a pr // Label a label to an issue or a pr
@ -26,17 +28,18 @@ type ListLabelsOptions struct {
} }
// ListRepoLabels list labels of one repository // ListRepoLabels list labels of one repository
func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*Label, error) { func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*Label, *Response, error) {
opt.setDefaults() opt.setDefaults()
labels := make([]*Label, 0, opt.PageSize) labels := make([]*Label, 0, opt.PageSize)
return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels?%s", owner, repo, opt.getURLQuery().Encode()), nil, nil, &labels) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels?%s", owner, repo, opt.getURLQuery().Encode()), nil, nil, &labels)
return labels, resp, err
} }
// GetRepoLabel get one label of repository by repo it // GetRepoLabel get one label of repository by repo it
// TODO: maybe we need get a label by name func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, *Response, error) {
func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, error) {
label := new(Label) label := new(Label)
return label, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label)
return label, resp, err
} }
// CreateLabelOption options for creating a label // CreateLabelOption options for creating a label
@ -47,8 +50,26 @@ type CreateLabelOption struct {
Description string `json:"description"` Description string `json:"description"`
} }
// Validate the CreateLabelOption struct
func (opt CreateLabelOption) Validate() error {
aw, err := regexp.MatchString("^#?[0-9,a-f,A-F]{6}$", opt.Color)
if err != nil {
return err
}
if !aw {
return fmt.Errorf("invalid color format")
}
if len(strings.TrimSpace(opt.Name)) == 0 {
return fmt.Errorf("empty name not allowed")
}
return nil
}
// CreateLabel create one label of repository // CreateLabel create one label of repository
func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, *Response, error) {
if err := opt.Validate(); err != nil {
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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
opt.Color = "#" + opt.Color opt.Color = "#" + opt.Color
@ -56,11 +77,13 @@ func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label,
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
label := new(Label) label := new(Label)
return label, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/labels", owner, repo),
jsonHeader, bytes.NewReader(body), label) jsonHeader, bytes.NewReader(body), label)
return label, resp, err
} }
// EditLabelOption options for editing a label // EditLabelOption options for editing a label
@ -70,27 +93,50 @@ type EditLabelOption struct {
Description *string `json:"description"` Description *string `json:"description"`
} }
// Validate the EditLabelOption struct
func (opt EditLabelOption) Validate() error {
if opt.Color != nil {
aw, err := regexp.MatchString("^#?[0-9,a-f,A-F]{6}$", *opt.Color)
if err != nil {
return err
}
if !aw {
return fmt.Errorf("invalid color format")
}
}
if opt.Name != nil {
if len(strings.TrimSpace(*opt.Name)) == 0 {
return fmt.Errorf("empty name not allowed")
}
}
return nil
}
// EditLabel modify one label with options // EditLabel modify one label with options
func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, error) { func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
label := new(Label) label := new(Label)
return label, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), label) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), label)
return label, resp, err
} }
// DeleteLabel delete one label of repository by id // DeleteLabel delete one label of repository by id
// TODO: maybe we need delete by name func (c *Client) DeleteLabel(owner, repo string, id int64) (*Response, error) {
func (c *Client) DeleteLabel(owner, repo string, id int64) error { _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil)
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil) return resp, err
return err
} }
// GetIssueLabels get labels of one issue via issue id // GetIssueLabels get labels of one issue via issue id
func (c *Client) GetIssueLabels(owner, repo string, index int64, opts ListLabelsOptions) ([]*Label, error) { func (c *Client) GetIssueLabels(owner, repo string, index int64, opts ListLabelsOptions) ([]*Label, *Response, error) {
labels := make([]*Label, 0, 5) labels := make([]*Label, 0, 5)
return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels)
return labels, resp, err
} }
// IssueLabelsOption a collection of labels // IssueLabelsOption a collection of labels
@ -100,34 +146,36 @@ type IssueLabelsOption struct {
} }
// AddIssueLabels add one or more labels to one issue // AddIssueLabels add one or more labels to one issue
func (c *Client) AddIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { func (c *Client) AddIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
var labels []*Label var labels []*Label
return labels, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels)
return labels, resp, err
} }
// ReplaceIssueLabels replace old labels of issue with new labels // ReplaceIssueLabels replace old labels of issue with new labels
func (c *Client) ReplaceIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { func (c *Client) ReplaceIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
var labels []*Label var labels []*Label
return labels, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) resp, err := c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels)
return labels, resp, err
} }
// DeleteIssueLabel delete one label of one issue by issue id and label id // DeleteIssueLabel delete one label of one issue by issue id and label id
// TODO: maybe we need delete by label name and issue id // TODO: maybe we need delete by label name and issue id
func (c *Client) DeleteIssueLabel(owner, repo string, index, label int64) error { func (c *Client) DeleteIssueLabel(owner, repo string, index, label int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, index, label), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, index, label), nil, nil)
return err return resp, err
} }
// ClearIssueLabels delete all the labels of one issue. // ClearIssueLabels delete all the labels of one issue.
func (c *Client) ClearIssueLabels(owner, repo string, index int64) error { func (c *Client) ClearIssueLabels(owner, repo string, index int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil)
return err return resp, err
} }

View File

@ -9,6 +9,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
"strings"
"time" "time"
) )
@ -20,6 +21,8 @@ type Milestone struct {
State StateType `json:"state"` State StateType `json:"state"`
OpenIssues int `json:"open_issues"` OpenIssues int `json:"open_issues"`
ClosedIssues int `json:"closed_issues"` ClosedIssues int `json:"closed_issues"`
Created time.Time `json:"created_at"`
Updated *time.Time `json:"updated_at"`
Closed *time.Time `json:"closed_at"` Closed *time.Time `json:"closed_at"`
Deadline *time.Time `json:"due_on"` Deadline *time.Time `json:"due_on"`
} }
@ -29,6 +32,7 @@ type ListMilestoneOption struct {
ListOptions ListOptions
// open, closed, all // open, closed, all
State StateType State StateType
Name string
} }
// QueryEncode turns options into querystring argument // QueryEncode turns options into querystring argument
@ -37,23 +41,40 @@ func (opt *ListMilestoneOption) QueryEncode() string {
if opt.State != "" { if opt.State != "" {
query.Add("state", string(opt.State)) query.Add("state", string(opt.State))
} }
if len(opt.Name) != 0 {
query.Add("name", opt.Name)
}
return query.Encode() return query.Encode()
} }
// ListRepoMilestones list all the milestones of one repository // ListRepoMilestones list all the milestones of one repository
func (c *Client) ListRepoMilestones(owner, repo string, opt ListMilestoneOption) ([]*Milestone, error) { func (c *Client) ListRepoMilestones(owner, repo string, opt ListMilestoneOption) ([]*Milestone, *Response, error) {
opt.setDefaults() opt.setDefaults()
milestones := make([]*Milestone, 0, opt.PageSize) milestones := make([]*Milestone, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/milestones", owner, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/milestones", owner, repo))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
return milestones, c.getParsedResponse("GET", link.String(), nil, nil, &milestones) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &milestones)
return milestones, resp, err
} }
// GetMilestone get one milestone by repo name and milestone id // GetMilestone get one milestone by repo name and milestone id
func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, error) { func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, *Response, error) {
milestone := new(Milestone) milestone := new(Milestone)
return milestone, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil, milestone) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil, milestone)
return milestone, resp, err
}
// GetMilestoneByName get one milestone by repo and milestone name
func (c *Client) GetMilestoneByName(owner, repo string, name string) (*Milestone, *Response, error) {
if c.CheckServerVersionConstraint(">=1.13") != nil {
// backwards compatibility mode
m, resp, err := c.resolveMilestoneByName(owner, repo, name)
return m, resp, err
}
milestone := new(Milestone)
resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), nil, nil, milestone)
return milestone, resp, err
} }
// CreateMilestoneOption options for creating a milestone // CreateMilestoneOption options for creating a milestone
@ -64,47 +85,129 @@ type CreateMilestoneOption struct {
Deadline *time.Time `json:"due_on"` Deadline *time.Time `json:"due_on"`
} }
// Validate the CreateMilestoneOption struct
func (opt CreateMilestoneOption) Validate() error {
if len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
return nil
}
// CreateMilestone create one milestone with options // CreateMilestone create one milestone with options
func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, error) { func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
milestone := new(Milestone) milestone := new(Milestone)
err = c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone)
// make creating closed milestones need gitea >= v1.13.0 // make creating closed milestones need gitea >= v1.13.0
// this make it backwards compatible // this make it backwards compatible
if err == nil && opt.State == StateClosed && milestone.State != StateClosed { if err == nil && opt.State == StateClosed && milestone.State != StateClosed {
closed := "closed" closed := StateClosed
return c.EditMilestone(owner, repo, milestone.ID, EditMilestoneOption{ return c.EditMilestone(owner, repo, milestone.ID, EditMilestoneOption{
State: &closed, State: &closed,
}) })
} }
return milestone, err return milestone, resp, err
} }
// EditMilestoneOption options for editing a milestone // EditMilestoneOption options for editing a milestone
type EditMilestoneOption struct { type EditMilestoneOption struct {
Title string `json:"title"` Title string `json:"title"`
Description *string `json:"description"` Description *string `json:"description"`
State *string `json:"state"` State *StateType `json:"state"`
Deadline *time.Time `json:"due_on"` Deadline *time.Time `json:"due_on"`
} }
// Validate the EditMilestoneOption struct
func (opt EditMilestoneOption) Validate() error {
if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
return nil
}
// EditMilestone modify milestone with options // EditMilestone modify milestone with options
func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, error) { func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil {
return nil, nil, err
}
milestone := new(Milestone)
resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), milestone)
return milestone, resp, err
}
// EditMilestoneByName modify milestone with options
func (c *Client) EditMilestoneByName(owner, repo string, name string, opt EditMilestoneOption) (*Milestone, *Response, error) {
if c.CheckServerVersionConstraint(">=1.13") != nil {
// backwards compatibility mode
m, _, err := c.resolveMilestoneByName(owner, repo, name)
if err != nil {
return nil, nil, err
}
return c.EditMilestone(owner, repo, m.ID, opt)
}
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, nil, err
}
milestone := new(Milestone)
resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), milestone)
return milestone, resp, err
}
// DeleteMilestone delete one milestone by id
func (c *Client) DeleteMilestone(owner, repo string, id int64) (*Response, error) {
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil)
return resp, err
}
// DeleteMilestoneByName delete one milestone by name
func (c *Client) DeleteMilestoneByName(owner, repo string, name string) (*Response, error) {
if c.CheckServerVersionConstraint(">=1.13") != nil {
// backwards compatibility mode
m, _, err := c.resolveMilestoneByName(owner, repo, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
milestone := new(Milestone) return c.DeleteMilestone(owner, repo, m.ID)
return milestone, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), milestone) }
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), nil, nil)
return resp, err
} }
// DeleteMilestone delete one milestone by milestone id // resolveMilestoneByName is a fallback method to find milestone id by name
func (c *Client) DeleteMilestone(owner, repo string, id int64) error { func (c *Client) resolveMilestoneByName(owner, repo, name string) (*Milestone, *Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil) for i := 1; ; i++ {
return err miles, resp, err := c.ListRepoMilestones(owner, repo, ListMilestoneOption{
ListOptions: ListOptions{
Page: i,
},
State: "all",
})
if err != nil {
return nil, nil, err
}
if len(miles) == 0 {
return nil, nil, fmt.Errorf("milestone '%s' do not exist", name)
}
for _, m := range miles {
if strings.ToLower(strings.TrimSpace(m.Title)) == strings.ToLower(strings.TrimSpace(name)) {
return m, resp, nil
}
}
}
} }

View File

@ -19,21 +19,23 @@ 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, 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, err return nil, nil, err
} }
reactions := make([]*Reaction, 0, 10) reactions := make([]*Reaction, 0, 10)
return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), nil, nil, &reactions) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), nil, nil, &reactions)
return reactions, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, err return nil, nil, err
} }
reactions := make([]*Reaction, 0, 10) reactions := make([]*Reaction, 0, 10)
return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), nil, nil, &reactions) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), nil, nil, &reactions)
return reactions, resp, err
} }
// editReactionOption contain the reaction type // editReactionOption contain the reaction type
@ -42,57 +44,61 @@ 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, 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, err return nil, nil, err
} }
reactionResponse := new(Reaction) reactionResponse := new(Reaction)
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index),
jsonHeader, bytes.NewReader(body), reactionResponse) jsonHeader, bytes.NewReader(body), reactionResponse)
return reactionResponse, resp, err
} }
// 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) 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
} }
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, err return nil, nil, err
} }
reactionResponse := new(Reaction) reactionResponse := new(Reaction)
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID),
jsonHeader, bytes.NewReader(body), reactionResponse) jsonHeader, bytes.NewReader(body), reactionResponse)
return reactionResponse, resp, err
} }
// 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) 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
} }
// swagger:operation DELETE /repos/{owner}/{repo}/issues/comments/{id}/reactions issue issueDeleteCommentReaction
body, err := json.Marshal(&editReactionOption{Reaction: reaction}) body, err := json.Marshal(&editReactionOption{Reaction: reaction})
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), _, resp, err := c.getResponse("DELETE",
fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID),
jsonHeader, bytes.NewReader(body)) jsonHeader, bytes.NewReader(body))
return err return resp, err
} }

View File

@ -16,27 +16,28 @@ type StopWatch struct {
} }
// GetMyStopwatches list all stopwatches // GetMyStopwatches list all stopwatches
func (c *Client) GetMyStopwatches() ([]*StopWatch, error) { func (c *Client) GetMyStopwatches() ([]*StopWatch, *Response, error) {
stopwatches := make([]*StopWatch, 0, 1) stopwatches := make([]*StopWatch, 0, 1)
return stopwatches, c.getParsedResponse("GET", "/user/stopwatches", nil, nil, &stopwatches) resp, err := c.getParsedResponse("GET", "/user/stopwatches", nil, nil, &stopwatches)
return stopwatches, resp, err
} }
// DeleteIssueStopwatch delete / cancel a specific stopwatch // DeleteIssueStopwatch delete / cancel a specific stopwatch
func (c *Client) DeleteIssueStopwatch(owner, repo string, index int64) error { func (c *Client) DeleteIssueStopwatch(owner, repo string, index int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/delete", owner, repo, index), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/delete", owner, repo, index), nil, nil)
return err return resp, err
} }
// StartIssueStopWatch starts a stopwatch for an existing issue for a given // StartIssueStopWatch starts a stopwatch for an existing issue for a given
// repository // repository
func (c *Client) StartIssueStopWatch(owner, repo string, index int64) error { func (c *Client) StartIssueStopWatch(owner, repo string, index int64) (*Response, error) {
_, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/start", owner, repo, index), nil, nil) _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/start", owner, repo, index), nil, nil)
return err return resp, err
} }
// StopIssueStopWatch stops an existing stopwatch for an issue in a given // StopIssueStopWatch stops an existing stopwatch for an issue in a given
// repository // repository
func (c *Client) StopIssueStopWatch(owner, repo string, index int64) error { func (c *Client) StopIssueStopWatch(owner, repo string, index int64) (*Response, error) {
_, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/stop", owner, repo, index), nil, nil) _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/stop", owner, repo, index), nil, nil)
return err return resp, err
} }

View File

@ -10,73 +10,75 @@ 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, 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, err return nil, nil, err
} }
subscribers := make([]*User, 0, 10) subscribers := make([]*User, 0, 10)
return subscribers, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions", owner, repo, index), nil, nil, &subscribers) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions", owner, repo, index), nil, nil, &subscribers)
return subscribers, resp, err
} }
// AddIssueSubscription Subscribe user to issue // AddIssueSubscription Subscribe user to issue
func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
} }
status, 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)
if err != nil { if err != nil {
return err return resp, err
} }
if status == http.StatusCreated { if status == http.StatusCreated {
return nil return resp, nil
} }
if status == http.StatusOK { if status == http.StatusOK {
return fmt.Errorf("already subscribed") return resp, fmt.Errorf("already subscribed")
} }
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }
// DeleteIssueSubscription unsubscribe user from issue // DeleteIssueSubscription unsubscribe user from issue
func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) 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.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
} }
status, 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)
if err != nil { if err != nil {
return err return resp, err
} }
if status == http.StatusCreated { if status == http.StatusCreated {
return nil return resp, nil
} }
if status == http.StatusOK { if status == http.StatusOK {
return fmt.Errorf("already unsubscribed") return resp, fmt.Errorf("already unsubscribed")
} }
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
wi := new(WatchInfo) wi := new(WatchInfo)
return wi, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/check", owner, repo, index), nil, nil, wi) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/check", owner, repo, index), nil, nil, wi)
return wi, resp, err
} }
// IssueSubscribe subscribe current user to an issue // IssueSubscribe subscribe current user to an issue
func (c *Client) IssueSubscribe(owner, repo string, index int64) error { func (c *Client) IssueSubscribe(owner, repo string, index int64) (*Response, error) {
u, err := c.GetMyUserInfo() u, _, err := c.GetMyUserInfo()
if err != nil { if err != nil {
return err return nil, err
} }
return c.AddIssueSubscription(owner, repo, index, u.UserName) return c.AddIssueSubscription(owner, repo, index, u.UserName)
} }
// IssueUnSubscribe unsubscribe current user from an issue // IssueUnSubscribe unsubscribe current user from an issue
func (c *Client) IssueUnSubscribe(owner, repo string, index int64) error { func (c *Client) IssueUnSubscribe(owner, repo string, index int64) (*Response, error) {
u, err := c.GetMyUserInfo() u, _, err := c.GetMyUserInfo()
if err != nil { if err != nil {
return err return nil, err
} }
return c.DeleteIssueSubscription(owner, repo, index, u.UserName) return c.DeleteIssueSubscription(owner, repo, index, u.UserName)
} }

View File

@ -26,42 +26,70 @@ 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, error) { func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, nil, err
}
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times/%s", owner, repo, user), nil, nil, &times) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times/%s", owner, repo, user), nil, nil, &times)
return times, resp, err
} }
// GetRepoTrackedTimes list tracked times of a repository // GetRepoTrackedTimes list tracked times of a repository
func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, error) { func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, nil, err
}
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, &times) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, &times)
return times, resp, err
} }
// GetMyTrackedTimes list tracked times of the current user // GetMyTrackedTimes list tracked times of the current user
func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, error) { func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, nil, err
}
times := make([]*TrackedTime, 0, 10) times := make([]*TrackedTime, 0, 10)
return times, c.getParsedResponse("GET", "/user/times", nil, nil, &times) resp, err := c.getParsedResponse("GET", "/user/times", nil, nil, &times)
return times, resp, err
} }
// AddTimeOption options for adding time to an issue // AddTimeOption options for adding time to an issue
type AddTimeOption struct { type AddTimeOption struct {
// time in seconds // time in seconds
Time int64 `json:"time" binding:"Required"` Time int64 `json:"time"`
// optional // optional
Created time.Time `json:"created"` Created time.Time `json:"created"`
// optional // optional
User string `json:"user_name"` User string `json:"user_name"`
} }
// Validate the AddTimeOption struct
func (opt AddTimeOption) Validate() error {
if opt.Time == 0 {
return fmt.Errorf("no time to add")
}
return nil
}
// 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, error) { func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, nil, err
}
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
t := new(TrackedTime) t := new(TrackedTime)
return t, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index),
jsonHeader, bytes.NewReader(body), t) jsonHeader, bytes.NewReader(body), t)
return t, resp, err
} }
// ListTrackedTimesOptions options for listing repository's tracked times // ListTrackedTimesOptions options for listing repository's tracked times
@ -70,20 +98,30 @@ 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, error) { func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrackedTimesOptions) ([]*TrackedTime, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return nil, nil, err
}
opt.setDefaults() opt.setDefaults()
times := make([]*TrackedTime, 0, opt.PageSize) times := make([]*TrackedTime, 0, opt.PageSize)
return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times?%s", owner, repo, index, opt.getURLQuery().Encode()), nil, nil, &times) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times?%s", owner, repo, index, opt.getURLQuery().Encode()), nil, nil, &times)
return times, resp, err
} }
// 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) error { func (c *Client) ResetIssueTime(owner, repo string, index int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil) if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
}
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil)
return resp, 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) error { func (c *Client) DeleteTime(owner, repo string, index, timeID int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil) if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err return nil, err
}
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil)
return resp, err
} }

View File

@ -29,16 +29,31 @@ type NotificationSubject struct {
Type string `json:"type" binding:"In(Issue,Pull,Commit)"` Type string `json:"type" binding:"In(Issue,Pull,Commit)"`
} }
// NotifyStatus notification status type
type NotifyStatus string
const (
// NotifyStatusUnread was not read
NotifyStatusUnread NotifyStatus = "unread"
// NotifyStatusRead was already read by user
NotifyStatusRead NotifyStatus = "read"
// NotifyStatusPinned notification is pinned by user
NotifyStatusPinned NotifyStatus = "pinned"
)
// ListNotificationOptions represents the filter options // ListNotificationOptions represents the filter options
type ListNotificationOptions struct { type ListNotificationOptions struct {
ListOptions ListOptions
Since time.Time Since time.Time
Before time.Time Before time.Time
Status []NotifyStatus
} }
// MarkNotificationOptions represents the filter options // MarkNotificationOptions represents the filter & modify options
type MarkNotificationOptions struct { type MarkNotificationOptions struct {
LastReadAt time.Time LastReadAt time.Time
Status []NotifyStatus
ToStatus NotifyStatus
} }
// QueryEncode encode options to url query // QueryEncode encode options to url query
@ -50,88 +65,134 @@ func (opt *ListNotificationOptions) QueryEncode() string {
if !opt.Before.IsZero() { if !opt.Before.IsZero() {
query.Add("before", opt.Before.Format(time.RFC3339)) query.Add("before", opt.Before.Format(time.RFC3339))
} }
for _, s := range opt.Status {
query.Add("status-types", string(s))
}
return query.Encode() return query.Encode()
} }
// Validate the CreateUserOption struct
func (opt ListNotificationOptions) Validate(c *Client) error {
if len(opt.Status) != 0 {
return c.CheckServerVersionConstraint(">=1.12.3")
}
return nil
}
// QueryEncode encode options to url query // QueryEncode encode options to url query
func (opt *MarkNotificationOptions) QueryEncode() string { func (opt *MarkNotificationOptions) QueryEncode() string {
query := make(url.Values) query := make(url.Values)
if !opt.LastReadAt.IsZero() { if !opt.LastReadAt.IsZero() {
query.Add("last_read_at", opt.LastReadAt.Format(time.RFC3339)) query.Add("last_read_at", opt.LastReadAt.Format(time.RFC3339))
} }
for _, s := range opt.Status {
query.Add("status-types", string(s))
}
if len(opt.ToStatus) != 0 {
query.Add("to-status", string(opt.ToStatus))
}
return query.Encode() return query.Encode()
} }
// Validate the CreateUserOption struct
func (opt MarkNotificationOptions) Validate(c *Client) error {
if len(opt.Status) != 0 || len(opt.ToStatus) != 0 {
return c.CheckServerVersionConstraint(">=1.12.3")
}
return nil
}
// CheckNotifications list users's notification threads // CheckNotifications list users's notification threads
func (c *Client) CheckNotifications() (int64, error) { func (c *Client) CheckNotifications() (int64, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return 0, err return 0, nil, err
} }
new := struct { new := struct {
New int64 `json:"new"` New int64 `json:"new"`
}{} }{}
return new.New, c.getParsedResponse("GET", "/notifications/new", jsonHeader, nil, &new) resp, err := c.getParsedResponse("GET", "/notifications/new", jsonHeader, nil, &new)
return new.New, resp, err
} }
// GetNotification get notification thread by ID // GetNotification get notification thread by ID
func (c *Client) GetNotification(id int64) (*NotificationThread, error) { func (c *Client) GetNotification(id int64) (*NotificationThread, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
thread := new(NotificationThread) thread := new(NotificationThread)
return thread, c.getParsedResponse("GET", fmt.Sprintf("/notifications/threads/%d", id), nil, nil, thread) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/notifications/threads/%d", id), nil, nil, thread)
return thread, resp, err
} }
// ReadNotification mark notification thread as read by ID // ReadNotification mark notification thread as read by ID
func (c *Client) ReadNotification(id int64) error { // 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) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err return nil, err
} }
_, err := c.getResponse("PATCH", fmt.Sprintf("/notifications/threads/%d", id), nil, nil) link := fmt.Sprintf("/notifications/threads/%d", id)
return err if len(status) != 0 {
link += fmt.Sprintf("?to-status=%s", status[0])
}
_, resp, err := c.getResponse("PATCH", link, nil, nil)
return resp, err
} }
// ListNotifications list users's notification threads // ListNotifications list users's notification threads
func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, error) { func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
}
if err := opt.Validate(c); err != nil {
return nil, nil, err
} }
link, _ := url.Parse("/notifications") link, _ := url.Parse("/notifications")
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
threads := make([]*NotificationThread, 0, 10) threads := make([]*NotificationThread, 0, 10)
return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &threads)
return threads, resp, err
} }
// ReadNotifications mark notification threads as read // ReadNotifications mark notification threads as read
func (c *Client) ReadNotifications(opt MarkNotificationOptions) error { func (c *Client) ReadNotifications(opt MarkNotificationOptions) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err return nil, err
}
if err := opt.Validate(c); err != nil {
return nil, err
} }
link, _ := url.Parse("/notifications") link, _ := url.Parse("/notifications")
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
_, err := c.getResponse("PUT", link.String(), nil, nil) _, resp, err := c.getResponse("PUT", link.String(), nil, nil)
return err return resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
}
if err := opt.Validate(c); err != nil {
return nil, nil, err
} }
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
threads := make([]*NotificationThread, 0, 10) threads := make([]*NotificationThread, 0, 10)
return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &threads)
return threads, resp, err
} }
// 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) error { func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err return nil, err
}
if err := opt.Validate(c); err != nil {
return nil, err
} }
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
_, err := c.getResponse("PUT", link.String(), nil, nil) _, resp, err := c.getResponse("PUT", link.String(), nil, nil)
return err return resp, err
} }

View File

@ -33,55 +33,59 @@ 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, error) { func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, *Response, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, e return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
oauth := new(Oauth2) oauth := new(Oauth2)
return oauth, c.getParsedResponse("POST", "/user/applications/oauth2", jsonHeader, bytes.NewReader(body), oauth) resp, err := c.getParsedResponse("POST", "/user/applications/oauth2", jsonHeader, bytes.NewReader(body), oauth)
return oauth, resp, err
} }
// 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, error) { func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, *Response, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, e return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
oauth := new(Oauth2) oauth := new(Oauth2)
return oauth, c.getParsedResponse("PATCH", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), jsonHeader, bytes.NewReader(body), oauth) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), jsonHeader, bytes.NewReader(body), oauth)
return oauth, resp, err
} }
// GetOauth2 a specific Oauth2 Application by ID. // GetOauth2 a specific Oauth2 Application by ID.
func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, error) { func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, *Response, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, e return nil, nil, err
} }
oauth2s := &Oauth2{} oauth2s := &Oauth2{}
return oauth2s, c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil, &oauth2s) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil, &oauth2s)
return oauth2s, resp, err
} }
// ListOauth2 all of your Oauth2 Applications. // ListOauth2 all of your Oauth2 Applications.
func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, error) { func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, *Response, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, e return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
oauth2s := make([]*Oauth2, 0, opt.PageSize) oauth2s := make([]*Oauth2, 0, opt.PageSize)
return oauth2s, c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2?%s", opt.getURLQuery().Encode()), nil, nil, &oauth2s) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2?%s", opt.getURLQuery().Encode()), nil, nil, &oauth2s)
return oauth2s, resp, err
} }
// DeleteOauth2 delete an Oauth2 application by ID // DeleteOauth2 delete an Oauth2 application by ID
func (c *Client) DeleteOauth2(oauth2id int64) error { func (c *Client) DeleteOauth2(oauth2id int64) (*Response, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return e return nil, err
} }
_, 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)
return err return resp, err
} }

View File

@ -23,51 +23,86 @@ type Organization struct {
Visibility string `json:"visibility"` Visibility string `json:"visibility"`
} }
// VisibleType defines the visibility
type VisibleType string
const (
// VisibleTypePublic Visible for everyone
VisibleTypePublic VisibleType = "public"
// VisibleTypeLimited Visible for every connected user
VisibleTypeLimited VisibleType = "limited"
// VisibleTypePrivate Visible only for organization's members
VisibleTypePrivate VisibleType = "private"
)
// ListOrgsOptions options for listing organizations // ListOrgsOptions options for listing organizations
type ListOrgsOptions struct { type ListOrgsOptions struct {
ListOptions ListOptions
} }
// ListMyOrgs list all of current user's organizations // ListMyOrgs list all of current user's organizations
func (c *Client) ListMyOrgs(opt ListOrgsOptions) ([]*Organization, error) { func (c *Client) ListMyOrgs(opt ListOrgsOptions) ([]*Organization, *Response, error) {
opt.setDefaults() opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize) orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/user/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs)
return orgs, resp, err
} }
// ListUserOrgs list all of some user's organizations // ListUserOrgs list all of some user's organizations
func (c *Client) ListUserOrgs(user string, opt ListOrgsOptions) ([]*Organization, error) { func (c *Client) ListUserOrgs(user string, opt ListOrgsOptions) ([]*Organization, *Response, error) {
opt.setDefaults() opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize) orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs?%s", user, opt.getURLQuery().Encode()), nil, nil, &orgs) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs?%s", user, opt.getURLQuery().Encode()), nil, nil, &orgs)
return orgs, resp, err
} }
// GetOrg get one organization by name // GetOrg get one organization by name
func (c *Client) GetOrg(orgname string) (*Organization, error) { func (c *Client) GetOrg(orgname string) (*Organization, *Response, error) {
org := new(Organization) org := new(Organization)
return org, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org)
return org, resp, err
} }
// CreateOrgOption options for creating an organization // CreateOrgOption options for creating an organization
type CreateOrgOption struct { type CreateOrgOption struct {
UserName string `json:"username"` Name string `json:"username"`
FullName string `json:"full_name"` FullName string `json:"full_name"`
Description string `json:"description"` Description string `json:"description"`
Website string `json:"website"` Website string `json:"website"`
Location string `json:"location"` Location string `json:"location"`
// possible values are `public` (default), `limited` or `private` Visibility VisibleType `json:"visibility"`
// enum: public,limited,private }
Visibility string `json:"visibility"`
// checkVisibilityOpt check if mode exist
func checkVisibilityOpt(v VisibleType) bool {
return v == VisibleTypePublic || v == VisibleTypeLimited || v == VisibleTypePrivate
}
// Validate the CreateOrgOption struct
func (opt CreateOrgOption) Validate() error {
if len(opt.Name) == 0 {
return fmt.Errorf("empty org name")
}
if len(opt.Visibility) != 0 && !checkVisibilityOpt(opt.Visibility) {
return fmt.Errorf("infalid bisibility option")
}
return nil
} }
// CreateOrg creates an organization // CreateOrg creates an organization
func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, error) { func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
org := new(Organization) org := new(Organization)
return org, c.getParsedResponse("POST", "/orgs", jsonHeader, bytes.NewReader(body), org) resp, err := c.getParsedResponse("POST", "/orgs", jsonHeader, bytes.NewReader(body), org)
return org, resp, err
} }
// EditOrgOption options for editing an organization // EditOrgOption options for editing an organization
@ -76,23 +111,32 @@ type EditOrgOption struct {
Description string `json:"description"` Description string `json:"description"`
Website string `json:"website"` Website string `json:"website"`
Location string `json:"location"` Location string `json:"location"`
// possible values are `public`, `limited` or `private` Visibility VisibleType `json:"visibility"`
// enum: public,limited,private }
Visibility string `json:"visibility"`
// Validate the EditOrgOption struct
func (opt EditOrgOption) Validate() error {
if len(opt.Visibility) != 0 && !checkVisibilityOpt(opt.Visibility) {
return fmt.Errorf("infalid bisibility option")
}
return nil
} }
// EditOrg modify one organization via options // EditOrg modify one organization via options
func (c *Client) EditOrg(orgname string, opt EditOrgOption) error { func (c *Client) EditOrg(orgname string, opt EditOrgOption) (*Response, error) {
if err := opt.Validate(); err != nil {
return nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// DeleteOrg deletes an organization // DeleteOrg deletes an organization
func (c *Client) DeleteOrg(orgname string) error { func (c *Client) DeleteOrg(orgname string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, nil)
return err return resp, err
} }

View File

@ -11,9 +11,9 @@ import (
) )
// DeleteOrgMembership remove a member from an organization // DeleteOrgMembership remove a member from an organization
func (c *Client) DeleteOrgMembership(org, user string) error { func (c *Client) DeleteOrgMembership(org, user string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
return err return resp, err
} }
// ListOrgMembershipOption list OrgMembership options // ListOrgMembershipOption list OrgMembership options
@ -22,77 +22,80 @@ type ListOrgMembershipOption struct {
} }
// ListOrgMembership list an organization's members // ListOrgMembership list an organization's members
func (c *Client) ListOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) { func (c *Client) ListOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/orgs/%s/members", url.PathEscape(org))) link, _ := url.Parse(fmt.Sprintf("/orgs/%s/members", url.PathEscape(org)))
link.RawQuery = opt.getURLQuery().Encode() link.RawQuery = opt.getURLQuery().Encode()
return users, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users)
return users, resp, err
} }
// ListPublicOrgMembership list an organization's members // ListPublicOrgMembership list an organization's members
func (c *Client) ListPublicOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) { func (c *Client) ListPublicOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/orgs/%s/public_members", url.PathEscape(org))) link, _ := url.Parse(fmt.Sprintf("/orgs/%s/public_members", url.PathEscape(org)))
link.RawQuery = opt.getURLQuery().Encode() link.RawQuery = opt.getURLQuery().Encode()
return users, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users)
return users, resp, err
} }
// CheckOrgMembership Check if a user is a member of an organization // CheckOrgMembership Check if a user is a member of an organization
func (c *Client) CheckOrgMembership(org, user string) (bool, error) { func (c *Client) CheckOrgMembership(org, user string) (bool, *Response, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
switch status { switch status {
case http.StatusNoContent: case http.StatusNoContent:
return true, nil return true, resp, nil
case http.StatusNotFound: case http.StatusNotFound:
return false, nil return false, resp, nil
default: default:
return false, fmt.Errorf("unexpected Status: %d", status) return false, resp, fmt.Errorf("unexpected Status: %d", status)
} }
} }
// CheckPublicOrgMembership Check if a user is a member of an organization // CheckPublicOrgMembership Check if a user is a member of an organization
func (c *Client) CheckPublicOrgMembership(org, user string) (bool, error) { func (c *Client) CheckPublicOrgMembership(org, user string) (bool, *Response, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
switch status { switch status {
case http.StatusNoContent: case http.StatusNoContent:
return true, nil return true, resp, nil
case http.StatusNotFound: case http.StatusNotFound:
return false, nil return false, resp, nil
default: default:
return false, fmt.Errorf("unexpected Status: %d", status) return false, resp, fmt.Errorf("unexpected Status: %d", status)
} }
} }
// SetPublicOrgMembership publicize/conceal a user's membership // SetPublicOrgMembership publicize/conceal a user's membership
func (c *Client) SetPublicOrgMembership(org, user string, visible bool) error { func (c *Client) SetPublicOrgMembership(org, user string, visible bool) (*Response, error) {
var ( var (
status int status int
err error err error
resp *Response
) )
if visible { if visible {
status, err = c.getStatusCode("PUT", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) status, resp, err = c.getStatusCode("PUT", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
} else { } else {
status, err = c.getStatusCode("DELETE", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) status, resp, err = c.getStatusCode("DELETE", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
} }
if err != nil { if err != nil {
return err return resp, err
} }
switch status { switch status {
case http.StatusNoContent: case http.StatusNoContent:
return nil return resp, nil
case http.StatusNotFound: case http.StatusNotFound:
return fmt.Errorf("forbidden") return resp, fmt.Errorf("forbidden")
default: default:
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }
} }

View File

@ -16,8 +16,9 @@ type Team struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Organization *Organization `json:"organization"` Organization *Organization `json:"organization"`
// enum: none,read,write,admin,owner Permission AccessMode `json:"permission"`
Permission string `json:"permission"` CanCreateOrgRepo bool `json:"can_create_org_repo"`
IncludesAllRepositories bool `json:"includes_all_repositories"`
// example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"]
Units []string `json:"units"` Units []string `json:"units"`
} }
@ -28,69 +29,119 @@ type ListTeamsOptions struct {
} }
// ListOrgTeams lists all teams of an organization // ListOrgTeams lists all teams of an organization
func (c *Client) ListOrgTeams(org string, opt ListTeamsOptions) ([]*Team, error) { func (c *Client) ListOrgTeams(org string, opt ListTeamsOptions) ([]*Team, *Response, error) {
opt.setDefaults() opt.setDefaults()
teams := make([]*Team, 0, opt.PageSize) teams := make([]*Team, 0, opt.PageSize)
return teams, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams?%s", org, opt.getURLQuery().Encode()), nil, nil, &teams) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams?%s", org, opt.getURLQuery().Encode()), nil, nil, &teams)
return teams, resp, err
} }
// ListMyTeams lists all the teams of the current user // ListMyTeams lists all the teams of the current user
func (c *Client) ListMyTeams(opt *ListTeamsOptions) ([]*Team, error) { func (c *Client) ListMyTeams(opt *ListTeamsOptions) ([]*Team, *Response, error) {
opt.setDefaults() opt.setDefaults()
teams := make([]*Team, 0, opt.PageSize) teams := make([]*Team, 0, opt.PageSize)
return teams, c.getParsedResponse("GET", fmt.Sprintf("/user/teams?%s", opt.getURLQuery().Encode()), nil, nil, &teams) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/teams?%s", opt.getURLQuery().Encode()), nil, nil, &teams)
return teams, resp, err
} }
// GetTeam gets a team by ID // GetTeam gets a team by ID
func (c *Client) GetTeam(id int64) (*Team, error) { func (c *Client) GetTeam(id int64) (*Team, *Response, error) {
t := new(Team) t := new(Team)
return t, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d", id), nil, nil, t) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d", id), nil, nil, t)
return t, resp, err
} }
// CreateTeamOption options for creating a team // CreateTeamOption options for creating a team
type CreateTeamOption struct { type CreateTeamOption struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
// enum: read,write,admin Permission AccessMode `json:"permission"`
Permission string `json:"permission"` CanCreateOrgRepo bool `json:"can_create_org_repo"`
IncludesAllRepositories bool `json:"includes_all_repositories"`
// example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"]
Units []string `json:"units"` Units []string `json:"units"`
} }
// Validate the CreateTeamOption struct
func (opt CreateTeamOption) Validate() error {
if opt.Permission == AccessModeOwner {
opt.Permission = AccessModeAdmin
} else if opt.Permission != AccessModeRead && opt.Permission != AccessModeWrite && opt.Permission != AccessModeAdmin {
return fmt.Errorf("permission mode invalid")
}
if len(opt.Name) == 0 {
return fmt.Errorf("name required")
}
if len(opt.Name) > 30 {
return fmt.Errorf("name to long")
}
if len(opt.Description) > 255 {
return fmt.Errorf("description to long")
}
return nil
}
// CreateTeam creates a team for an organization // CreateTeam creates a team for an organization
func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, error) { func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
t := new(Team) t := new(Team)
return t, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/teams", org), jsonHeader, bytes.NewReader(body), t) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/teams", org), jsonHeader, bytes.NewReader(body), t)
return t, resp, err
} }
// EditTeamOption options for editing a team // EditTeamOption options for editing a team
type EditTeamOption struct { type EditTeamOption struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description *string `json:"description"`
// enum: read,write,admin Permission AccessMode `json:"permission"`
Permission string `json:"permission"` CanCreateOrgRepo *bool `json:"can_create_org_repo"`
IncludesAllRepositories *bool `json:"includes_all_repositories"`
// example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"]
Units []string `json:"units"` Units []string `json:"units"`
} }
// Validate the EditTeamOption struct
func (opt EditTeamOption) Validate() error {
if opt.Permission == AccessModeOwner {
opt.Permission = AccessModeAdmin
} else if opt.Permission != AccessModeRead && opt.Permission != AccessModeWrite && opt.Permission != AccessModeAdmin {
return fmt.Errorf("permission mode invalid")
}
if len(opt.Name) == 0 {
return fmt.Errorf("name required")
}
if len(opt.Name) > 30 {
return fmt.Errorf("name to long")
}
if opt.Description != nil && len(*opt.Description) > 255 {
return fmt.Errorf("description to long")
}
return nil
}
// EditTeam edits a team of an organization // EditTeam edits a team of an organization
func (c *Client) EditTeam(id int64, opt EditTeamOption) error { func (c *Client) EditTeam(id int64, opt EditTeamOption) (*Response, error) {
if err := opt.Validate(); err != nil {
return nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PATCH", fmt.Sprintf("/teams/%d", id), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/teams/%d", id), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// DeleteTeam deletes a team of an organization // DeleteTeam deletes a team of an organization
func (c *Client) DeleteTeam(id int64) error { func (c *Client) DeleteTeam(id int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d", id), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d", id), nil, nil)
return err return resp, err
} }
// ListTeamMembersOptions options for listing team's members // ListTeamMembersOptions options for listing team's members
@ -99,28 +150,30 @@ type ListTeamMembersOptions struct {
} }
// ListTeamMembers lists all members of a team // ListTeamMembers lists all members of a team
func (c *Client) ListTeamMembers(id int64, opt ListTeamMembersOptions) ([]*User, error) { func (c *Client) ListTeamMembers(id int64, opt ListTeamMembersOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
members := make([]*User, 0, opt.PageSize) members := make([]*User, 0, opt.PageSize)
return members, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members?%s", id, opt.getURLQuery().Encode()), nil, nil, &members) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members?%s", id, opt.getURLQuery().Encode()), nil, nil, &members)
return members, resp, err
} }
// GetTeamMember gets a member of a team // GetTeamMember gets a member of a team
func (c *Client) GetTeamMember(id int64, user string) (*User, error) { func (c *Client) GetTeamMember(id int64, user string) (*User, *Response, error) {
m := new(User) m := new(User)
return m, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil, m) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil, m)
return m, resp, err
} }
// AddTeamMember adds a member to a team // AddTeamMember adds a member to a team
func (c *Client) AddTeamMember(id int64, user string) error { func (c *Client) AddTeamMember(id int64, user string) (*Response, error) {
_, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil)
return err return resp, err
} }
// RemoveTeamMember removes a member from a team // RemoveTeamMember removes a member from a team
func (c *Client) RemoveTeamMember(id int64, user string) error { func (c *Client) RemoveTeamMember(id int64, user string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil)
return err return resp, err
} }
// ListTeamRepositoriesOptions options for listing team's repositories // ListTeamRepositoriesOptions options for listing team's repositories
@ -129,20 +182,21 @@ type ListTeamRepositoriesOptions struct {
} }
// ListTeamRepositories lists all repositories of a team // ListTeamRepositories lists all repositories of a team
func (c *Client) ListTeamRepositories(id int64, opt ListTeamRepositoriesOptions) ([]*Repository, error) { func (c *Client) ListTeamRepositories(id int64, opt ListTeamRepositoriesOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize) repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos?%s", id, opt.getURLQuery().Encode()), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos?%s", id, opt.getURLQuery().Encode()), nil, nil, &repos)
return repos, resp, err
} }
// AddTeamRepository adds a repository to a team // AddTeamRepository adds a repository to a team
func (c *Client) AddTeamRepository(id int64, org, repo string) error { func (c *Client) AddTeamRepository(id int64, org, repo string) (*Response, error) {
_, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil)
return err return resp, err
} }
// RemoveTeamRepository removes a repository from a team // RemoveTeamRepository removes a repository from a team
func (c *Client) RemoveTeamRepository(id int64, org, repo string) error { func (c *Client) RemoveTeamRepository(id int64, org, repo string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil)
return err return resp, err
} }

View File

@ -1,27 +0,0 @@
// Copyright 2019 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
// VisibleType defines the visibility (Organization only)
type VisibleType int
const (
// VisibleTypePublic Visible for everyone
VisibleTypePublic VisibleType = iota
// VisibleTypeLimited Visible for every connected user
VisibleTypeLimited
// VisibleTypePrivate Visible only for organization's members
VisibleTypePrivate
)
// ExtractKeysFromMapString provides a slice of keys from map
func ExtractKeysFromMapString(in map[string]VisibleType) (keys []string) {
for k := range in {
keys = append(keys, k)
}
return
}

View File

@ -10,6 +10,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
"strings"
"time" "time"
) )
@ -35,6 +36,7 @@ type PullRequest struct {
Assignee *User `json:"assignee"` Assignee *User `json:"assignee"`
Assignees []*User `json:"assignees"` Assignees []*User `json:"assignees"`
State StateType `json:"state"` State StateType `json:"state"`
IsLocked bool `json:"is_locked"`
Comments int `json:"comments"` Comments int `json:"comments"`
HTMLURL string `json:"html_url"` HTMLURL string `json:"html_url"`
@ -96,19 +98,21 @@ func (opt *ListPullRequestsOptions) QueryEncode() string {
} }
// ListRepoPullRequests list PRs of one repository // ListRepoPullRequests list PRs of one repository
func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, *Response, error) {
opt.setDefaults() opt.setDefaults()
prs := make([]*PullRequest, 0, opt.PageSize) prs := make([]*PullRequest, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls", owner, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls", owner, repo))
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
return prs, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &prs) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &prs)
return prs, resp, err
} }
// GetPullRequest get information of one PR // GetPullRequest get information of one PR
func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest, error) { func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest, *Response, error) {
pr := new(PullRequest) pr := new(PullRequest)
return pr, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), nil, nil, pr) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), nil, nil, pr)
return pr, resp, err
} }
// CreatePullRequestOption options when creating a pull request // CreatePullRequestOption options when creating a pull request
@ -125,14 +129,16 @@ type CreatePullRequestOption struct {
} }
// CreatePullRequest create pull request with options // CreatePullRequest create pull request with options
func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOption) (*PullRequest, error) { func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOption) (*PullRequest, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
pr := new(PullRequest) pr := new(PullRequest)
return pr, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/pulls", owner, repo),
jsonHeader, bytes.NewReader(body), pr) jsonHeader, bytes.NewReader(body), pr)
return pr, resp, err
} }
// EditPullRequestOption options when modify pull request // EditPullRequestOption options when modify pull request
@ -148,15 +154,33 @@ type EditPullRequestOption struct {
Deadline *time.Time `json:"due_date"` Deadline *time.Time `json:"due_date"`
} }
// Validate the EditPullRequestOption struct
func (opt EditPullRequestOption) Validate(c *Client) error {
if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
if len(opt.Base) != 0 {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return fmt.Errorf("can not change base gitea to old")
}
}
return nil
}
// EditPullRequest modify pull request with PR id and options // EditPullRequest modify pull request with PR id and options
func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, error) { func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, *Response, error) {
if err := opt.Validate(c); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
pr := new(PullRequest) pr := new(PullRequest)
return pr, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), resp, err := c.getParsedResponse("PATCH",
fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index),
jsonHeader, bytes.NewReader(body), pr) jsonHeader, bytes.NewReader(body), pr)
return pr, resp, err
} }
// MergePullRequestOption options when merging a pull request // MergePullRequestOption options when merging a pull request
@ -166,31 +190,64 @@ type MergePullRequestOption struct {
Message string `json:"MergeMessageField"` Message string `json:"MergeMessageField"`
} }
// MergePullRequest merge a PR to repository by PR id // Validate the MergePullRequestOption struct
func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, error) { func (opt MergePullRequestOption) Validate(c *Client) error {
if opt.Style == MergeStyleSquash { if opt.Style == MergeStyleSquash {
if err := c.CheckServerVersionConstraint(">=1.11.5"); err != nil { if err := c.CheckServerVersionConstraint(">=1.11.5"); err != nil {
return false, err return err
} }
} }
return nil
}
// MergePullRequest merge a PR to repository by PR id
func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, *Response, error) {
if err := opt.Validate(c); err != nil {
return false, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return false, err return false, nil, err
} }
status, err := c.getStatusCode("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), jsonHeader, bytes.NewReader(body)) status, resp, err := c.getStatusCode("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), jsonHeader, bytes.NewReader(body))
if err != nil { if err != nil {
return false, err return false, resp, err
} }
return status == 200, nil return status == 200, resp, nil
} }
// IsPullRequestMerged test if one PR is merged to one repository // IsPullRequestMerged test if one PR is merged to one repository
func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, error) { func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, *Response, error) {
statusCode, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
return statusCode == 204, nil return status == 204, resp, nil
}
// 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) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
r, _, err2 := c.GetRepo(owner, repo)
if err2 != nil {
return nil, nil, err
}
if r.Private {
return nil, nil, err
}
return c.getWebResponse("GET", fmt.Sprintf("/%s/%s/pulls/%d.%s", owner, repo, index, kind), nil)
}
return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d.%s", owner, repo, index, kind), nil, nil)
}
// GetPullRequestPatch gets the .patch file as bytes for a PR
func (c *Client) GetPullRequestPatch(owner, repo string, index int64) ([]byte, *Response, error) {
return c.getPullRequestDiffOrPatch(owner, repo, "patch", index)
}
// GetPullRequestDiff gets the .diff file as bytes for a PR
func (c *Client) GetPullRequestDiff(owner, repo string, index int64) ([]byte, *Response, error) {
return c.getPullRequestDiffOrPatch(owner, repo, "diff", index)
} }

View File

@ -9,6 +9,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
"strings"
"time" "time"
) )
@ -40,7 +41,6 @@ type PullReview struct {
Stale bool `json:"stale"` Stale bool `json:"stale"`
Official bool `json:"official"` Official bool `json:"official"`
CodeCommentsCount int `json:"comments_count"` CodeCommentsCount int `json:"comments_count"`
// swagger:strfmt date-time
Submitted time.Time `json:"submitted_at"` Submitted time.Time `json:"submitted_at"`
HTMLURL string `json:"html_url"` HTMLURL string `json:"html_url"`
@ -54,9 +54,7 @@ type PullReviewComment struct {
Reviewer *User `json:"user"` Reviewer *User `json:"user"`
ReviewID int64 `json:"pull_request_review_id"` ReviewID int64 `json:"pull_request_review_id"`
// swagger:strfmt date-time
Created time.Time `json:"created_at"` Created time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated time.Time `json:"updated_at"` Updated time.Time `json:"updated_at"`
Path string `json:"path"` Path string `json:"path"`
@ -100,10 +98,42 @@ type ListPullReviewsOptions struct {
ListOptions ListOptions
} }
// Validate the CreatePullReviewOptions struct
func (opt CreatePullReviewOptions) Validate() error {
if opt.State != ReviewStateApproved && len(strings.TrimSpace(opt.Body)) == 0 {
return fmt.Errorf("body is empty")
}
for i := range opt.Comments {
if err := opt.Comments[i].Validate(); err != nil {
return err
}
}
return nil
}
// Validate the SubmitPullReviewOptions struct
func (opt SubmitPullReviewOptions) Validate() error {
if opt.State != ReviewStateApproved && len(strings.TrimSpace(opt.Body)) == 0 {
return fmt.Errorf("body is empty")
}
return nil
}
// Validate the CreatePullReviewComment struct
func (opt CreatePullReviewComment) Validate() error {
if len(strings.TrimSpace(opt.Body)) == 0 {
return fmt.Errorf("body is empty")
}
if opt.NewLineNum != 0 && opt.OldLineNum != 0 {
return fmt.Errorf("old and new line num are set, cant identify the code comment position")
}
return nil
}
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
opt.setDefaults() opt.setDefaults()
rs := make([]*PullReview, 0, opt.PageSize) rs := make([]*PullReview, 0, opt.PageSize)
@ -111,74 +141,79 @@ func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullRe
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index))
link.RawQuery = opt.ListOptions.getURLQuery().Encode() link.RawQuery = opt.ListOptions.getURLQuery().Encode()
return rs, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rs) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rs)
return rs, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
r := new(PullReview) r := new(PullReview)
return r, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil, &r) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil, &r)
} return r, resp, err
// ListPullReviewsCommentsOptions options for listing PullReviewsComments
type ListPullReviewsCommentsOptions struct {
ListOptions
} }
// 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, opt ListPullReviewsCommentsOptions) ([]*PullReviewComment, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
opt.setDefaults() rcl := make([]*PullReviewComment, 0, 4)
rcl := make([]*PullReviewComment, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d/comments", owner, repo, index, id)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d/comments", owner, repo, index, id))
link.RawQuery = opt.ListOptions.getURLQuery().Encode()
return rcl, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rcl) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rcl)
return rcl, resp, err
} }
// 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) 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err return nil, err
} }
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil)
return err return resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
}
if err := opt.Validate(); err != nil {
return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
r := new(PullReview) r := new(PullReview)
return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index),
jsonHeader, bytes.NewReader(body), r) jsonHeader, bytes.NewReader(body), r)
return r, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
}
if err := opt.Validate(); err != nil {
return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
r := new(PullReview) r := new(PullReview)
return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id),
jsonHeader, bytes.NewReader(body), r) jsonHeader, bytes.NewReader(body), r)
return r, resp, err
} }

View File

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings"
"time" "time"
) )
@ -35,22 +36,22 @@ type ListReleasesOptions struct {
} }
// ListReleases list releases of a repository // ListReleases list releases of a repository
func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Release, error) { func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Release, *Response, error) {
opt.setDefaults() opt.setDefaults()
releases := make([]*Release, 0, opt.PageSize) releases := make([]*Release, 0, opt.PageSize)
err := c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases?%s", user, repo, opt.getURLQuery().Encode()), fmt.Sprintf("/repos/%s/%s/releases?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &releases) nil, nil, &releases)
return releases, err return releases, resp, err
} }
// GetRelease get a release of a repository // GetRelease get a release of a repository
func (c *Client) GetRelease(user, repo string, id int64) (*Release, error) { func (c *Client) GetRelease(user, repo string, id int64) (*Release, *Response, error) {
r := new(Release) r := new(Release)
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),
nil, nil, &r) nil, nil, &r)
return r, err return r, resp, err
} }
// CreateReleaseOption options when creating a release // CreateReleaseOption options when creating a release
@ -63,17 +64,28 @@ type CreateReleaseOption struct {
IsPrerelease bool `json:"prerelease"` IsPrerelease bool `json:"prerelease"`
} }
// Validate the CreateReleaseOption struct
func (opt CreateReleaseOption) Validate() error {
if len(strings.TrimSpace(opt.Title)) == 0 {
return fmt.Errorf("title is empty")
}
return nil
}
// CreateRelease create a release // CreateRelease create a release
func (c *Client) CreateRelease(user, repo string, form CreateReleaseOption) (*Release, error) { func (c *Client) CreateRelease(user, repo string, opt CreateReleaseOption) (*Release, *Response, error) {
body, err := json.Marshal(form) if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
r := new(Release) r := new(Release)
err = c.getParsedResponse("POST", resp, err := c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/releases", user, repo), fmt.Sprintf("/repos/%s/%s/releases", user, repo),
jsonHeader, bytes.NewReader(body), r) jsonHeader, bytes.NewReader(body), r)
return r, err return r, resp, err
} }
// EditReleaseOption options when editing a release // EditReleaseOption options when editing a release
@ -87,22 +99,22 @@ type EditReleaseOption struct {
} }
// EditRelease edit a release // EditRelease edit a release
func (c *Client) EditRelease(user, repo string, id int64, form EditReleaseOption) (*Release, error) { func (c *Client) EditRelease(user, repo string, id int64, form EditReleaseOption) (*Release, *Response, error) {
body, err := json.Marshal(form) body, err := json.Marshal(form)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
r := new(Release) r := new(Release)
err = c.getParsedResponse("PATCH", resp, err := c.getParsedResponse("PATCH",
fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id),
jsonHeader, bytes.NewReader(body), r) jsonHeader, bytes.NewReader(body), r)
return r, err return r, resp, err
} }
// DeleteRelease delete a release from a repository // DeleteRelease delete a release from a repository
func (c *Client) DeleteRelease(user, repo string, id int64) error { func (c *Client) DeleteRelease(user, repo string, id int64) (*Response, error) {
_, err := c.getResponse("DELETE", _, resp, err := c.getResponse("DELETE",
fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id),
nil, nil) nil, nil)
return err return resp, err
} }

View File

@ -1,4 +1,5 @@
// Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
@ -9,6 +10,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
"strings"
"time" "time"
) )
@ -57,23 +59,39 @@ type Repository struct {
AvatarURL string `json:"avatar_url"` AvatarURL string `json:"avatar_url"`
} }
// RepoType represent repo type
type RepoType string
const (
// RepoTypeNone dont specify a type
RepoTypeNone RepoType = ""
// RepoTypeSource is the default repo type
RepoTypeSource RepoType = "source"
// RepoTypeFork is a repo witch was forked from an other one
RepoTypeFork RepoType = "fork"
// RepoTypeMirror represents an mirror repo
RepoTypeMirror RepoType = "mirror"
)
// ListReposOptions options for listing repositories // ListReposOptions options for listing repositories
type ListReposOptions struct { type ListReposOptions struct {
ListOptions ListOptions
} }
// ListMyRepos lists all repositories for the authenticated user that has access to. // ListMyRepos lists all repositories for the authenticated user that has access to.
func (c *Client) ListMyRepos(opt ListReposOptions) ([]*Repository, error) { func (c *Client) ListMyRepos(opt ListReposOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize) repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/user/repos?%s", opt.getURLQuery().Encode()), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/repos?%s", opt.getURLQuery().Encode()), nil, nil, &repos)
return repos, resp, err
} }
// ListUserRepos list all repositories of one user by user's name // ListUserRepos list all repositories of one user by user's name
func (c *Client) ListUserRepos(user string, opt ListReposOptions) ([]*Repository, error) { func (c *Client) ListUserRepos(user string, opt ListReposOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize) repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos?%s", user, opt.getURLQuery().Encode()), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos?%s", user, opt.getURLQuery().Encode()), nil, nil, &repos)
return repos, resp, err
} }
// ListOrgReposOptions options for a organization's repositories // ListOrgReposOptions options for a organization's repositories
@ -82,26 +100,62 @@ type ListOrgReposOptions struct {
} }
// ListOrgRepos list all repositories of one organization by organization's name // ListOrgRepos list all repositories of one organization by organization's name
func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repository, error) { func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize) repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos?%s", org, opt.getURLQuery().Encode()), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos?%s", org, opt.getURLQuery().Encode()), nil, nil, &repos)
return repos, resp, err
} }
// SearchRepoOptions options for searching repositories // SearchRepoOptions options for searching repositories
type SearchRepoOptions struct { type SearchRepoOptions struct {
ListOptions ListOptions
// The keyword to query
Keyword string Keyword string
Topic bool // Limit search to repositories with keyword as topic
IncludeDesc bool KeywordIsTopic bool
UID int64 // Include search of keyword within repository description
PriorityOwnerID int64 KeywordInDescription bool
StarredBy int64
Private bool /*
Template bool User Filter
Mode string */
Exclusive bool
// Repo Owner
OwnerID int64
// Stared By UserID
StarredByUserID int64
/*
Repo Attributes
*/
// pubic, private or all repositories (defaults to all)
IsPrivate *bool
// archived, non-archived or all repositories (defaults to all)
IsArchived *bool
// Exclude template repos from search
ExcludeTemplate bool
// Filter by "fork", "source", "mirror"
Type RepoType
/*
Sort Filters
*/
// sort repos by attribute. Supported values are "alpha", "created", "updated", "size", and "id". Default is "alpha"
Sort string Sort string
// sort order, either "asc" (ascending) or "desc" (descending). Default is "asc", ignored if "sort" is not specified.
Order string
// Repo owner to prioritize in the results
PrioritizedByOwnerID int64
/*
Cover EdgeCases
*/
// if set all other options are ignored and this string is used as query
RawQuery string
} }
// QueryEncode turns options into querystring argument // QueryEncode turns options into querystring argument
@ -110,34 +164,46 @@ func (opt *SearchRepoOptions) QueryEncode() string {
if opt.Keyword != "" { if opt.Keyword != "" {
query.Add("q", opt.Keyword) query.Add("q", opt.Keyword)
} }
if opt.KeywordIsTopic {
query.Add("topic", fmt.Sprintf("%t", opt.Topic)) query.Add("topic", "true")
query.Add("includeDesc", fmt.Sprintf("%t", opt.IncludeDesc)) }
if opt.KeywordInDescription {
if opt.UID > 0 { query.Add("includeDesc", "true")
query.Add("uid", fmt.Sprintf("%d", opt.UID))
} }
if opt.PriorityOwnerID > 0 { // User Filter
query.Add("priority_owner_id", fmt.Sprintf("%d", opt.PriorityOwnerID)) if opt.OwnerID > 0 {
query.Add("uid", fmt.Sprintf("%d", opt.OwnerID))
query.Add("exclusive", "true")
}
if opt.StarredByUserID > 0 {
query.Add("starredBy", fmt.Sprintf("%d", opt.StarredByUserID))
} }
if opt.StarredBy > 0 { // Repo Attributes
query.Add("starredBy", fmt.Sprintf("%d", opt.StarredBy)) if opt.IsPrivate != nil {
query.Add("is_private", fmt.Sprintf("%v", opt.IsPrivate))
}
if opt.IsArchived != nil {
query.Add("archived", fmt.Sprintf("%v", opt.IsArchived))
}
if opt.ExcludeTemplate {
query.Add("template", "false")
}
if len(opt.Type) != 0 {
query.Add("mode", string(opt.Type))
} }
query.Add("private", fmt.Sprintf("%t", opt.Private)) // Sort Filters
query.Add("template", fmt.Sprintf("%t", opt.Template))
if opt.Mode != "" {
query.Add("mode", opt.Mode)
}
query.Add("exclusive", fmt.Sprintf("%t", opt.Exclusive))
if opt.Sort != "" { if opt.Sort != "" {
query.Add("sort", opt.Sort) query.Add("sort", opt.Sort)
} }
if opt.PrioritizedByOwnerID > 0 {
query.Add("priority_owner_id", fmt.Sprintf("%d", opt.PrioritizedByOwnerID))
}
if opt.Order != "" {
query.Add("order", opt.Order)
}
return query.Encode() return query.Encode()
} }
@ -147,21 +213,33 @@ type searchRepoResponse struct {
} }
// SearchRepos searches for repositories matching the given filters // SearchRepos searches for repositories matching the given filters
func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) { func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, *Response, error) {
opt.setDefaults() opt.setDefaults()
resp := new(searchRepoResponse) repos := new(searchRepoResponse)
link, _ := url.Parse("/repos/search") link, _ := url.Parse("/repos/search")
link.RawQuery = opt.QueryEncode()
err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) if len(opt.RawQuery) != 0 {
return resp.Repos, err link.RawQuery = opt.RawQuery
} else {
link.RawQuery = opt.QueryEncode()
// IsPrivate only works on gitea >= 1.12.0
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil && opt.IsPrivate != nil {
if *opt.IsPrivate {
// private repos only not supported on gitea <= 1.11.x
return nil, nil, err
}
link.Query().Add("private", "false")
}
}
resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &repos)
return repos.Repos, resp, err
} }
// CreateRepoOption options when creating repository // CreateRepoOption options when creating repository
type CreateRepoOption struct { type CreateRepoOption struct {
// Name of the repository to create // Name of the repository to create
//
Name string `json:"name"` Name string `json:"name"`
// Description of the repository to create // Description of the repository to create
Description string `json:"description"` Description string `json:"description"`
@ -181,30 +259,47 @@ type CreateRepoOption struct {
DefaultBranch string `json:"default_branch"` DefaultBranch string `json:"default_branch"`
} }
// Validate the CreateRepoOption struct
func (opt CreateRepoOption) Validate() error {
if len(strings.TrimSpace(opt.Name)) == 0 {
return fmt.Errorf("name is empty")
}
return nil
}
// CreateRepo creates a repository for authenticated user. // CreateRepo creates a repository for authenticated user.
func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) { func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo) resp, err := c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo)
return repo, resp, err
} }
// 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, error) { func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo)
return repo, resp, err
} }
// GetRepo returns information of a repository of given owner. // GetRepo returns information of a repository of given owner.
func (c *Client) GetRepo(owner, reponame string) (*Repository, error) { func (c *Client) GetRepo(owner, reponame string) (*Repository, *Response, error) {
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo)
return repo, resp, err
} }
// EditRepoOption options when editing a repository's properties // EditRepoOption options when editing a repository's properties
@ -242,49 +337,54 @@ type EditRepoOption struct {
} }
// EditRepo edit the properties of a repository // EditRepo edit the properties of a repository
func (c *Client) EditRepo(owner, reponame string, opt EditRepoOption) (*Repository, error) { func (c *Client) EditRepo(owner, reponame string, opt EditRepoOption) (*Repository, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s", owner, reponame), jsonHeader, bytes.NewReader(body), repo) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s", owner, reponame), jsonHeader, bytes.NewReader(body), repo)
return repo, resp, err
} }
// DeleteRepo deletes a repository of user or organization. // DeleteRepo deletes a repository of user or organization.
func (c *Client) DeleteRepo(owner, repo string) error { func (c *Client) DeleteRepo(owner, repo string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil)
return err return resp, err
}
// MigrateRepoOption options for migrating a repository from an external service
type MigrateRepoOption struct {
CloneAddr string `json:"clone_addr"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
UID int `json:"uid"`
RepoName string `json:"repo_name"`
Mirror bool `json:"mirror"`
Private bool `json:"private"`
Description string `json:"description"`
}
// MigrateRepo migrates a repository from other Git hosting sources for the
// authenticated user.
//
// To migrate a repository for a organization, the authenticated user must be a
// owner of the specified organization.
func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo)
} }
// MirrorSync adds a mirrored repository to the mirror sync queue. // MirrorSync adds a mirrored repository to the mirror sync queue.
func (c *Client) MirrorSync(owner, repo string) error { func (c *Client) MirrorSync(owner, repo string) (*Response, error) {
_, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil) _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil)
return err return resp, err
}
// GetRepoLanguages return language stats of a repo
func (c *Client) GetRepoLanguages(owner, repo string) (map[string]int64, *Response, error) {
langMap := make(map[string]int64)
data, resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/languages", owner, repo), jsonHeader, nil)
if err != nil {
return nil, resp, err
}
if err = json.Unmarshal(data, &langMap); err != nil {
return nil, resp, err
}
return langMap, resp, nil
}
// ArchiveType represent supported archive formats by gitea
type ArchiveType string
const (
// ZipArchive represent zip format
ZipArchive ArchiveType = ".zip"
// TarGZArchive represent tar.gz format
TarGZArchive ArchiveType = ".tar.gz"
)
// GetArchive get an archive of a repository by git reference
// e.g.: ref -> master, 70b7c74b33, v1.2.1, ...
func (c *Client) GetArchive(owner, repo, ref string, ext ArchiveType) ([]byte, *Response, error) {
return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/archive/%s%s", owner, repo, url.PathEscape(ref), ext), nil, nil)
} }

View File

@ -6,6 +6,8 @@
package gitea package gitea
import ( import (
"bytes"
"encoding/json"
"fmt" "fmt"
"time" "time"
) )
@ -63,29 +65,70 @@ type ListRepoBranchesOptions struct {
} }
// ListRepoBranches list all the branches of one repository // ListRepoBranches list all the branches of one repository
func (c *Client) ListRepoBranches(user, repo string, opt ListRepoBranchesOptions) ([]*Branch, error) { func (c *Client) ListRepoBranches(user, repo string, opt ListRepoBranchesOptions) ([]*Branch, *Response, error) {
opt.setDefaults() opt.setDefaults()
branches := make([]*Branch, 0, opt.PageSize) branches := make([]*Branch, 0, opt.PageSize)
return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &branches) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &branches)
return branches, resp, err
} }
// GetRepoBranch get one branch's information of one repository // GetRepoBranch get one branch's information of one repository
func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, *Response, error) {
b := new(Branch) b := new(Branch)
if err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b); err != nil { resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b)
return nil, err if err != nil {
return nil, resp, err
} }
return b, nil return b, resp, nil
} }
// DeleteRepoBranch delete a branch in a repository // DeleteRepoBranch delete a branch in a repository
func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, error) { func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return false, err return false, nil, err
} }
status, 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)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
return status == 204, nil return status == 204, resp, nil
}
// CreateBranchOption options when creating a branch in a repository
type CreateBranchOption struct {
// Name of the branch to create
BranchName string `json:"new_branch_name"`
// Name of the old branch to create from (optional)
OldBranchName string `json:"old_branch_name"`
}
// Validate the CreateBranchOption struct
func (opt CreateBranchOption) Validate() error {
if len(opt.BranchName) == 0 {
return fmt.Errorf("BranchName is empty")
}
if len(opt.BranchName) > 100 {
return fmt.Errorf("BranchName to long")
}
if len(opt.OldBranchName) > 100 {
return fmt.Errorf("OldBranchName to long")
}
return nil
}
// CreateBranch creates a branch for a user's repository
func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
if err := opt.Validate(); err != nil {
return nil, nil, err
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, nil, err
}
branch := new(Branch)
resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branches", owner, repo), jsonHeader, bytes.NewReader(body), branch)
return branch, resp, err
} }

View File

@ -34,9 +34,7 @@ type BranchProtection struct {
DismissStaleApprovals bool `json:"dismiss_stale_approvals"` DismissStaleApprovals bool `json:"dismiss_stale_approvals"`
RequireSignedCommits bool `json:"require_signed_commits"` RequireSignedCommits bool `json:"require_signed_commits"`
ProtectedFilePatterns string `json:"protected_file_patterns"` ProtectedFilePatterns string `json:"protected_file_patterns"`
// swagger:strfmt date-time
Created time.Time `json:"created_at"` Created time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated time.Time `json:"updated_at"` Updated time.Time `json:"updated_at"`
} }
@ -93,56 +91,60 @@ 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
bps := make([]*BranchProtection, 0, 5) bps := make([]*BranchProtection, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo))
link.RawQuery = opt.getURLQuery().Encode() link.RawQuery = opt.getURLQuery().Encode()
return bps, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &bps) resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &bps)
return bps, resp, err
} }
// GetBranchProtection gets a branch protection // GetBranchProtection gets a branch protection
func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, error) { func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
return bp, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil, bp) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil, bp)
return bp, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
return bp, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo), jsonHeader, bytes.NewReader(body), bp) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo), jsonHeader, bytes.NewReader(body), bp)
return bp, resp, err
} }
// 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
bp := new(BranchProtection) bp := new(BranchProtection)
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
return bp, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), bp) resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), bp)
return bp, resp, err
} }
// DeleteBranchProtection deletes a branch protection for a repo // DeleteBranchProtection deletes a branch protection for a repo
func (c *Client) DeleteBranchProtection(owner, repo, name string) error { func (c *Client) DeleteBranchProtection(owner, repo, name string) (*Response, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err return nil, err
} }
_, 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)
return err return resp, err
} }

View File

@ -16,44 +16,82 @@ type ListCollaboratorsOptions struct {
} }
// ListCollaborators list a repository's collaborators // ListCollaborators list a repository's collaborators
func (c *Client) ListCollaborators(user, repo string, opt ListCollaboratorsOptions) ([]*User, error) { func (c *Client) ListCollaborators(user, repo string, opt ListCollaboratorsOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
collaborators := make([]*User, 0, opt.PageSize) collaborators := make([]*User, 0, opt.PageSize)
return collaborators, c.getParsedResponse("GET", resp, err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/collaborators?%s", user, repo, opt.getURLQuery().Encode()), fmt.Sprintf("/repos/%s/%s/collaborators?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &collaborators) nil, nil, &collaborators)
return collaborators, resp, err
} }
// IsCollaborator check if a user is a collaborator of a repository // IsCollaborator check if a user is a collaborator of a repository
func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, *Response, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil) status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
if status == 204 { if status == 204 {
return true, nil return true, resp, nil
} }
return false, nil return false, resp, nil
} }
// AddCollaboratorOption options when adding a user as a collaborator of a repository // AddCollaboratorOption options when adding a user as a collaborator of a repository
type AddCollaboratorOption struct { type AddCollaboratorOption struct {
Permission *string `json:"permission"` Permission *AccessMode `json:"permission"`
}
// AccessMode represent the grade of access you have to something
type AccessMode string
const (
// AccessModeNone no access
AccessModeNone AccessMode = "none"
// AccessModeRead read access
AccessModeRead AccessMode = "read"
// AccessModeWrite write access
AccessModeWrite AccessMode = "write"
// AccessModeAdmin admin access
AccessModeAdmin AccessMode = "admin"
// AccessModeOwner owner
AccessModeOwner AccessMode = "owner"
)
// Validate the AddCollaboratorOption struct
func (opt AddCollaboratorOption) Validate() error {
if opt.Permission != nil {
if *opt.Permission == AccessModeOwner {
*opt.Permission = AccessModeAdmin
return nil
}
if *opt.Permission == AccessModeNone {
opt.Permission = nil
return nil
}
if *opt.Permission != AccessModeRead && *opt.Permission != AccessModeWrite && *opt.Permission != AccessModeAdmin {
return fmt.Errorf("permission mode invalid")
}
}
return nil
} }
// AddCollaborator add some user as a collaborator of a repository // AddCollaborator add some user as a collaborator of a repository
func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) error { func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) (*Response, error) {
if err := opt.Validate(); err != nil {
return nil, err
}
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// DeleteCollaborator remove a collaborator from a repository // DeleteCollaborator remove a collaborator from a repository
func (c *Client) DeleteCollaborator(user, repo, collaborator string) error { func (c *Client) DeleteCollaborator(user, repo, collaborator string) (*Response, error) {
_, err := c.getResponse("DELETE", _, resp, err := c.getResponse("DELETE",
fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil) fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil)
return err return resp, err
} }

View File

@ -55,9 +55,10 @@ type CommitDateOptions struct {
} }
// GetSingleCommit returns a single commit // GetSingleCommit returns a single commit
func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, error) { func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, *Response, error) {
commit := new(Commit) commit := new(Commit)
return commit, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/commits/%s", user, repo, commitID), nil, nil, &commit) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/commits/%s", user, repo, commitID), nil, nil, &commit)
return commit, resp, err
} }
// ListCommitOptions list commit options // ListCommitOptions list commit options
@ -77,10 +78,11 @@ func (opt *ListCommitOptions) QueryEncode() string {
} }
// ListRepoCommits return list of commits from a repo // ListRepoCommits return list of commits from a repo
func (c *Client) ListRepoCommits(user, repo string, opt ListCommitOptions) ([]*Commit, error) { func (c *Client) ListRepoCommits(user, repo string, opt ListCommitOptions) ([]*Commit, *Response, error) {
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/commits", user, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/commits", user, repo))
opt.setDefaults() opt.setDefaults()
commits := make([]*Commit, 0, opt.PageSize) commits := make([]*Commit, 0, opt.PageSize)
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
return commits, c.getParsedResponse("GET", link.String(), nil, nil, &commits) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &commits)
return commits, resp, err
} }

View File

@ -114,74 +114,76 @@ type FileDeleteResponse struct {
// GetFile downloads a file of repository, ref can be branch/tag/commit. // GetFile downloads a file of repository, ref can be branch/tag/commit.
// e.g.: ref -> master, tree -> macaron.go(no leading slash) // e.g.: ref -> master, tree -> macaron.go(no leading slash)
func (c *Client) GetFile(user, repo, ref, tree string) ([]byte, error) { func (c *Client) GetFile(user, repo, ref, tree string) ([]byte, *Response, error) {
return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/raw/%s/%s", user, repo, ref, tree), nil, nil) return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/raw/%s/%s", user, repo, ref, tree), nil, nil)
} }
// GetContents get the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir // GetContents get the metadata and contents (if a file) of an entry in a repository, or a list of entries if a dir
// ref is optional // ref is optional
func (c *Client) GetContents(owner, repo, ref, filepath string) (*ContentsResponse, error) { func (c *Client) GetContents(owner, repo, ref, filepath string) (*ContentsResponse, *Response, error) {
cr := new(ContentsResponse) cr := new(ContentsResponse)
return cr, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", owner, repo, filepath, ref), jsonHeader, nil, cr) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", owner, repo, filepath, ref), jsonHeader, nil, cr)
return cr, resp, err
} }
// CreateFile create a file in a repository // CreateFile create a file in a repository
func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, error) { func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, *Response, error) {
var err error var err error
if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil {
return nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
fr := new(FileResponse) fr := new(FileResponse)
return fr, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr)
return fr, resp, err
} }
// UpdateFile update a file in a repository // UpdateFile update a file in a repository
func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, error) { func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, *Response, error) {
var err error var err error
if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil {
return nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
fr := new(FileResponse) fr := new(FileResponse)
return fr, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr) resp, err := c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr)
return fr, resp, err
} }
// DeleteFile delete a file from repository // DeleteFile delete a file from repository
func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) error { func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) (*Response, error) {
var err error var err error
if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil {
return err return nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body)) status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body))
if err != nil { if err != nil {
return err return resp, err
} }
if status != 200 && status != 204 { if status != 200 && status != 204 {
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }
return nil return resp, nil
} }
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 err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { if c.CheckServerVersionConstraint(">=1.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
} }

View File

@ -45,32 +45,35 @@ func (opt *ListDeployKeysOptions) QueryEncode() string {
} }
// ListDeployKeys list all the deploy keys of one repository // ListDeployKeys list all the deploy keys of one repository
func (c *Client) ListDeployKeys(user, repo string, opt ListDeployKeysOptions) ([]*DeployKey, error) { func (c *Client) ListDeployKeys(user, repo string, opt ListDeployKeysOptions) ([]*DeployKey, *Response, error) {
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/keys", user, repo)) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/keys", user, repo))
opt.setDefaults() opt.setDefaults()
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
keys := make([]*DeployKey, 0, opt.PageSize) keys := make([]*DeployKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", link.String(), nil, nil, &keys) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &keys)
return keys, resp, err
} }
// GetDeployKey get one deploy key with key id // GetDeployKey get one deploy key with key id
func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, error) { func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, *Response, error) {
key := new(DeployKey) key := new(DeployKey)
return key, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key)
return key, resp, err
} }
// CreateDeployKey options when create one deploy key // CreateDeployKey options when create one deploy key
func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, error) { func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
key := new(DeployKey) key := new(DeployKey)
return key, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key)
return key, resp, err
} }
// DeleteDeployKey delete deploy key with key id // DeleteDeployKey delete deploy key with key id
func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) error { func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil)
return err return resp, err
} }

115
vendor/code.gitea.io/sdk/gitea/repo_migrate.go generated vendored Normal file
View File

@ -0,0 +1,115 @@
// 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 (
"bytes"
"encoding/json"
"fmt"
)
// GitServiceType represents a git service
type GitServiceType string
const (
// GitServicePlain represents a plain git service
GitServicePlain GitServiceType = "git"
//GitServiceGithub represents github.com
GitServiceGithub GitServiceType = "github"
// GitServiceGitlab represents a gitlab service
GitServiceGitlab GitServiceType = "gitlab"
// Not supported jet
// // GitServiceGitea represents a gitea service
// GitServiceGitea GitServiceType = "gitea"
// // GitServiceGogs represents a gogs service
// GitServiceGogs GitServiceType = "gogs"
)
// MigrateRepoOption options for migrating a repository from an external service
type MigrateRepoOption struct {
RepoName string `json:"repo_name"`
RepoOwner string `json:"repo_owner"`
// deprecated use RepoOwner
RepoOwnerID int64 `json:"uid"`
CloneAddr string `json:"clone_addr"`
Service GitServiceType `json:"service"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
AuthToken string `json:"auth_token"`
Mirror bool `json:"mirror"`
Private bool `json:"private"`
Description string `json:"description"`
Wiki bool `json:"wiki"`
Milestones bool `json:"milestones"`
Labels bool `json:"labels"`
Issues bool `json:"issues"`
PullRequests bool `json:"pull_requests"`
Releases bool `json:"releases"`
}
// Validate the MigrateRepoOption struct
func (opt *MigrateRepoOption) Validate() error {
// check user options
if len(opt.CloneAddr) == 0 {
return fmt.Errorf("CloneAddr required")
}
if len(opt.RepoName) == 0 {
return fmt.Errorf("RepoName required")
} else if len(opt.RepoName) > 100 {
return fmt.Errorf("RepoName to long")
}
if len(opt.Description) > 255 {
return fmt.Errorf("Description to long")
}
switch opt.Service {
case GitServiceGithub:
if len(opt.AuthToken) == 0 {
return fmt.Errorf("github require token authentication")
}
}
return nil
}
// MigrateRepo migrates a repository from other Git hosting sources for the authenticated user.
//
// To migrate a repository for a organization, the authenticated user must be a
// owner of the specified organization.
func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, *Response, error) {
if err := opt.Validate(); err != nil {
return nil, nil, err
}
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
if len(opt.AuthToken) != 0 {
// gitea <= 1.12 dont understand AuthToken
opt.AuthUsername = opt.AuthToken
opt.AuthPassword, opt.AuthToken = "", ""
}
if len(opt.RepoOwner) != 0 {
// gitea <= 1.12 dont understand RepoOwner
u, _, err := c.GetUserInfo(opt.RepoOwner)
if err != nil {
return nil, nil, err
}
opt.RepoOwnerID = u.ID
} else if opt.RepoOwnerID == 0 {
// gitea <= 1.12 require RepoOwnerID
u, _, err := c.GetMyUserInfo()
if err != nil {
return nil, nil, err
}
opt.RepoOwnerID = u.ID
}
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, nil, err
}
repo := new(Repository)
resp, err := c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo)
return repo, resp, err
}

View File

@ -26,44 +26,44 @@ type GitObject struct {
} }
// GetRepoRef get one ref's information of one repository // GetRepoRef get one ref's information of one repository
func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, error) { func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, *Response, error) {
ref = strings.TrimPrefix(ref, "refs/") ref = strings.TrimPrefix(ref, "refs/")
r := new(Reference) r := new(Reference)
err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r)
if _, ok := err.(*json.UnmarshalTypeError); ok { if _, ok := err.(*json.UnmarshalTypeError); ok {
// Multiple refs // Multiple refs
return nil, errors.New("no exact match found for this ref") return nil, resp, errors.New("no exact match found for this ref")
} else if err != nil { } else if err != nil {
return nil, err return nil, resp, err
} }
return r, nil return r, resp, nil
} }
// GetRepoRefs get list of ref's information of one repository // GetRepoRefs get list of ref's information of one repository
func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, error) { func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, *Response, error) {
ref = strings.TrimPrefix(ref, "refs/") ref = strings.TrimPrefix(ref, "refs/")
resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil) data, resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil)
if err != nil { if err != nil {
return nil, err return nil, resp, err
} }
// Attempt to unmarshal single returned ref. // Attempt to unmarshal single returned ref.
r := new(Reference) r := new(Reference)
refErr := json.Unmarshal(resp, r) refErr := json.Unmarshal(data, r)
if refErr == nil { if refErr == nil {
return []*Reference{r}, nil return []*Reference{r}, resp, nil
} }
// Attempt to unmarshal multiple refs. // Attempt to unmarshal multiple refs.
var rs []*Reference var rs []*Reference
refsErr := json.Unmarshal(resp, &rs) refsErr := json.Unmarshal(data, &rs)
if refsErr == nil { if refsErr == nil {
if len(rs) == 0 { if len(rs) == 0 {
return nil, errors.New("unexpected response: an array of refs with length 0") return nil, resp, errors.New("unexpected response: an array of refs with length 0")
} }
return rs, nil return rs, resp, nil
} }
return nil, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr) return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr)
} }

View File

@ -23,8 +23,9 @@ type ListRepoTagsOptions struct {
} }
// ListRepoTags list all the branches of one repository // ListRepoTags list all the branches of one repository
func (c *Client) ListRepoTags(user, repo string, opt ListRepoTagsOptions) ([]*Tag, error) { func (c *Client) ListRepoTags(user, repo string, opt ListRepoTagsOptions) ([]*Tag, *Response, error) {
opt.setDefaults() opt.setDefaults()
tags := make([]*Tag, 0, opt.PageSize) tags := make([]*Tag, 0, opt.PageSize)
return tags, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &tags) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &tags)
return tags, resp, err
} }

View File

@ -21,38 +21,38 @@ type topicsList struct {
} }
// ListRepoTopics list all repository's topics // ListRepoTopics list all repository's topics
func (c *Client) ListRepoTopics(user, repo string, opt ListRepoTopicsOptions) ([]string, error) { func (c *Client) ListRepoTopics(user, repo string, opt ListRepoTopicsOptions) ([]string, *Response, error) {
opt.setDefaults() opt.setDefaults()
list := new(topicsList) list := new(topicsList)
err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, list) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, list)
if err != nil { if err != nil {
return nil, err return nil, resp, err
} }
return list.Topics, nil return list.Topics, resp, nil
} }
// SetRepoTopics replaces the list of repo's topics // SetRepoTopics replaces the list of repo's topics
func (c *Client) SetRepoTopics(user, repo string, list []string) error { func (c *Client) SetRepoTopics(user, repo string, list []string) (*Response, error) {
l := topicsList{Topics: list} l := topicsList{Topics: list}
body, err := json.Marshal(&l) body, err := json.Marshal(&l)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics", user, repo), jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics", user, repo), jsonHeader, bytes.NewReader(body))
return err return resp, err
} }
// AddRepoTopic adds a topic to a repo's topics list // AddRepoTopic adds a topic to a repo's topics list
func (c *Client) AddRepoTopic(user, repo, topic string) error { func (c *Client) AddRepoTopic(user, repo, topic string) (*Response, error) {
_, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil)
return err return resp, err
} }
// DeleteRepoTopic deletes a topic from repo's topics list // DeleteRepoTopic deletes a topic from repo's topics list
func (c *Client) DeleteRepoTopic(user, repo, topic string) error { func (c *Client) DeleteRepoTopic(user, repo, topic string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil)
return err return resp, err
} }

View File

@ -19,14 +19,15 @@ 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, 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.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err return nil, nil, err
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
repo := new(Repository) repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/transfer", owner, reponame), jsonHeader, bytes.NewReader(body), repo) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/transfer", owner, reponame), jsonHeader, bytes.NewReader(body), repo)
return repo, resp, err
} }

View File

@ -30,11 +30,12 @@ type GitTreeResponse struct {
// GetTrees downloads a file of repository, ref can be branch/tag/commit. // GetTrees downloads a file of repository, ref can be branch/tag/commit.
// e.g.: ref -> master, tree -> macaron.go(no leading slash) // e.g.: ref -> master, tree -> macaron.go(no leading slash)
func (c *Client) GetTrees(user, repo, ref string, recursive bool) (*GitTreeResponse, error) { func (c *Client) GetTrees(user, repo, ref string, recursive bool) (*GitTreeResponse, *Response, error) {
trees := new(GitTreeResponse) trees := new(GitTreeResponse)
var path = fmt.Sprintf("/repos/%s/%s/git/trees/%s", user, repo, ref) var path = fmt.Sprintf("/repos/%s/%s/git/trees/%s", user, repo, ref)
if recursive { if recursive {
path += "?recursive=1" path += "?recursive=1"
} }
return trees, c.getParsedResponse("GET", path, nil, nil, trees) resp, err := c.getParsedResponse("GET", path, nil, nil, trees)
return trees, resp, err
} }

View File

@ -21,53 +21,55 @@ type WatchInfo struct {
} }
// GetWatchedRepos list all the watched repos of user // GetWatchedRepos list all the watched repos of user
func (c *Client) GetWatchedRepos(user string) ([]*Repository, error) { func (c *Client) GetWatchedRepos(user string) ([]*Repository, *Response, error) {
repos := make([]*Repository, 0, 10) repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), nil, nil, &repos)
return repos, resp, err
} }
// GetMyWatchedRepos list repositories watched by the authenticated user // GetMyWatchedRepos list repositories watched by the authenticated user
func (c *Client) GetMyWatchedRepos() ([]*Repository, error) { func (c *Client) GetMyWatchedRepos() ([]*Repository, *Response, error) {
repos := make([]*Repository, 0, 10) repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/user/subscriptions"), nil, nil, &repos) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/subscriptions"), nil, nil, &repos)
return repos, resp, err
} }
// CheckRepoWatch check if the current user is watching a repo // CheckRepoWatch check if the current user is watching a repo
func (c *Client) CheckRepoWatch(repoUser, repoName string) (bool, error) { func (c *Client) CheckRepoWatch(repoUser, repoName string) (bool, *Response, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil)
if err != nil { if err != nil {
return false, err return false, resp, err
} }
switch status { switch status {
case http.StatusNotFound: case http.StatusNotFound:
return false, nil return false, resp, nil
case http.StatusOK: case http.StatusOK:
return true, nil return true, resp, nil
default: default:
return false, fmt.Errorf("unexpected Status: %d", status) return false, resp, fmt.Errorf("unexpected Status: %d", status)
} }
} }
// WatchRepo start to watch a repository // WatchRepo start to watch a repository
func (c *Client) WatchRepo(repoUser, repoName string) error { func (c *Client) WatchRepo(repoUser, repoName string) (*Response, error) {
status, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) status, resp, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil)
if err != nil { if err != nil {
return err return resp, err
} }
if status == http.StatusOK { if status == http.StatusOK {
return nil return resp, nil
} }
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }
// UnWatchRepo stop to watch a repository // UnWatchRepo stop to watch a repository
func (c *Client) UnWatchRepo(repoUser, repoName string) error { func (c *Client) UnWatchRepo(repoUser, repoName string) (*Response, error) {
status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil)
if err != nil { if err != nil {
return err return resp, err
} }
if status == http.StatusNoContent { if status == http.StatusNoContent {
return nil return resp, nil
} }
return fmt.Errorf("unexpected Status: %d", status) return resp, fmt.Errorf("unexpected Status: %d", status)
} }

72
vendor/code.gitea.io/sdk/gitea/settings.go generated vendored Normal file
View File

@ -0,0 +1,72 @@
// 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
// GlobalUISettings represent the global ui settings of a gitea instance witch is exposed by API
type GlobalUISettings struct {
AllowedReactions []string `json:"allowed_reactions"`
}
// GlobalRepoSettings represent the global repository settings of a gitea instance witch is exposed by API
type GlobalRepoSettings struct {
MirrorsDisabled bool `json:"mirrors_disabled"`
HTTPGitDisabled bool `json:"http_git_disabled"`
}
// GlobalAPISettings contains global api settings exposed by it
type GlobalAPISettings struct {
MaxResponseItems int `json:"max_response_items"`
DefaultPagingNum int `json:"default_paging_num"`
DefaultGitTreesPerPage int `json:"default_git_trees_per_page"`
DefaultMaxBlobSize int64 `json:"default_max_blob_size"`
}
// GlobalAttachmentSettings contains global Attachment settings exposed by API
type GlobalAttachmentSettings struct {
Enabled bool `json:"enabled"`
AllowedTypes string `json:"allowed_types"`
MaxSize int64 `json:"max_size"`
MaxFiles int `json:"max_files"`
}
// GetGlobalUISettings get global ui settings witch are exposed by API
func (c *Client) GetGlobalUISettings() (*GlobalUISettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
conf := new(GlobalUISettings)
resp, err := c.getParsedResponse("GET", "/settings/ui", jsonHeader, nil, &conf)
return conf, resp, err
}
// GetGlobalRepoSettings get global repository settings witch are exposed by API
func (c *Client) GetGlobalRepoSettings() (*GlobalRepoSettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
conf := new(GlobalRepoSettings)
resp, err := c.getParsedResponse("GET", "/settings/repository", jsonHeader, nil, &conf)
return conf, resp, err
}
// GetGlobalAPISettings get global api settings witch are exposed by it
func (c *Client) GetGlobalAPISettings() (*GlobalAPISettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
conf := new(GlobalAPISettings)
resp, err := c.getParsedResponse("GET", "/settings/api", jsonHeader, nil, &conf)
return conf, resp, err
}
// GetGlobalAttachmentSettings get global repository settings witch are exposed by API
func (c *Client) GetGlobalAttachmentSettings() (*GlobalAttachmentSettings, *Response, error) {
if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil {
return nil, nil, err
}
conf := new(GlobalAttachmentSettings)
resp, err := c.getParsedResponse("GET", "/settings/attachment", jsonHeader, nil, &conf)
return conf, resp, err
}

View File

@ -50,13 +50,14 @@ type CreateStatusOption struct {
} }
// CreateStatus creates a new Status for a given Commit // CreateStatus creates a new Status for a given Commit
func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, *Response, error) {
body, err := json.Marshal(&opts) body, err := json.Marshal(&opts)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
status := new(Status) status := new(Status)
return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status)
return status, resp, err
} }
// ListStatusesOption options for listing a repository's commit's statuses // ListStatusesOption options for listing a repository's commit's statuses
@ -65,10 +66,11 @@ type ListStatusesOption struct {
} }
// ListStatuses returns all statuses for a given Commit // ListStatuses returns all statuses for a given Commit
func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, error) { func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, *Response, error) {
opt.setDefaults() opt.setDefaults()
statuses := make([]*Status, 0, opt.PageSize) statuses := make([]*Status, 0, opt.PageSize)
return statuses, 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, sha, opt.getURLQuery().Encode()), nil, nil, &statuses)
return statuses, resp, err
} }
// CombinedStatus holds the combined state of several statuses for a single commit // CombinedStatus holds the combined state of several statuses for a single commit
@ -83,7 +85,8 @@ 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, error) { func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, *Response, error) {
status := new(CombinedStatus) status := new(CombinedStatus)
return status, 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, sha), nil, nil, status)
return status, resp, err
} }

View File

@ -29,15 +29,15 @@ type User struct {
} }
// GetUserInfo get user info by user's name // GetUserInfo get user info by user's name
func (c *Client) GetUserInfo(user string) (*User, error) { func (c *Client) GetUserInfo(user string) (*User, *Response, error) {
u := new(User) u := new(User)
err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u)
return u, err return u, resp, err
} }
// GetMyUserInfo get user info of current user // GetMyUserInfo get user info of current user
func (c *Client) GetMyUserInfo() (*User, error) { func (c *Client) GetMyUserInfo() (*User, *Response, error) {
u := new(User) u := new(User)
err := c.getParsedResponse("GET", "/user", nil, nil, u) resp, err := c.getParsedResponse("GET", "/user", nil, nil, u)
return u, err return u, resp, err
} }

View File

@ -9,6 +9,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"reflect"
) )
// AccessToken represents an API access token. // AccessToken represents an API access token.
@ -25,13 +26,14 @@ type ListAccessTokensOptions struct {
} }
// ListAccessTokens lists all the access tokens of user // ListAccessTokens lists all the access tokens of user
func (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { func (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, *Response, error) {
if len(c.username) == 0 { if len(c.username) == 0 {
return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") return nil, nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed")
} }
opts.setDefaults() opts.setDefaults()
tokens := make([]*AccessToken, 0, opts.PageSize) tokens := make([]*AccessToken, 0, opts.PageSize)
return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens?%s", c.username, opts.getURLQuery().Encode()), jsonHeader, nil, &tokens) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens?%s", c.username, opts.getURLQuery().Encode()), jsonHeader, nil, &tokens)
return tokens, resp, err
} }
// CreateAccessTokenOption options when create access token // CreateAccessTokenOption options when create access token
@ -40,23 +42,39 @@ type CreateAccessTokenOption struct {
} }
// CreateAccessToken create one access token with options // CreateAccessToken create one access token with options
func (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, error) { func (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, *Response, error) {
if len(c.username) == 0 { if len(c.username) == 0 {
return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") return nil, nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed")
} }
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
t := new(AccessToken) t := new(AccessToken)
return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", c.username), jsonHeader, bytes.NewReader(body), t) resp, err := c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", c.username), jsonHeader, bytes.NewReader(body), t)
return t, resp, err
} }
// DeleteAccessToken delete token with key id // DeleteAccessToken delete token, identified by ID and if not available by name
func (c *Client) DeleteAccessToken(keyID int64) error { func (c *Client) DeleteAccessToken(value interface{}) (*Response, error) {
if len(c.username) == 0 { if len(c.username) == 0 {
return fmt.Errorf("\"username\" not set: only BasicAuth allowed") return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed")
} }
_, err := c.getResponse("DELETE", fmt.Sprintf("/users/%s/tokens/%d", c.username, keyID), jsonHeader, nil)
return err var token = ""
switch reflect.ValueOf(value).Kind() {
case reflect.Int64:
token = fmt.Sprintf("%d", value.(int64))
case reflect.String:
if err := c.CheckServerVersionConstraint(">= 1.13.0"); err != nil {
return nil, err
}
token = value.(string)
default:
return nil, fmt.Errorf("only string and int64 supported")
}
_, resp, err := c.getResponse("DELETE", fmt.Sprintf("/users/%s/tokens/%s", c.username, token), jsonHeader, nil)
return resp, err
} }

View File

@ -23,10 +23,11 @@ type ListEmailsOptions struct {
} }
// ListEmails all the email addresses of user // ListEmails all the email addresses of user
func (c *Client) ListEmails(opt ListEmailsOptions) ([]*Email, error) { func (c *Client) ListEmails(opt ListEmailsOptions) ([]*Email, *Response, error) {
opt.setDefaults() opt.setDefaults()
emails := make([]*Email, 0, opt.PageSize) emails := make([]*Email, 0, opt.PageSize)
return emails, c.getParsedResponse("GET", fmt.Sprintf("/user/emails?%s", opt.getURLQuery().Encode()), nil, nil, &emails) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/emails?%s", opt.getURLQuery().Encode()), nil, nil, &emails)
return emails, resp, err
} }
// CreateEmailOption options when creating email addresses // CreateEmailOption options when creating email addresses
@ -36,13 +37,14 @@ type CreateEmailOption struct {
} }
// AddEmail add one email to current user with options // AddEmail add one email to current user with options
func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, error) { func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
emails := make([]*Email, 0, 3) emails := make([]*Email, 0, 3)
return emails, c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), &emails) resp, err := c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), &emails)
return emails, resp, err
} }
// DeleteEmailOption options when deleting email addresses // DeleteEmailOption options when deleting email addresses
@ -52,11 +54,11 @@ type DeleteEmailOption struct {
} }
// DeleteEmail delete one email of current users' // DeleteEmail delete one email of current users'
func (c *Client) DeleteEmail(opt DeleteEmailOption) error { func (c *Client) DeleteEmail(opt DeleteEmailOption) (*Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return err return nil, err
} }
_, err = c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body)) _, resp, err := c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body))
return err return resp, err
} }

View File

@ -12,17 +12,19 @@ type ListFollowersOptions struct {
} }
// ListMyFollowers list all the followers of current user // ListMyFollowers list all the followers of current user
func (c *Client) ListMyFollowers(opt ListFollowersOptions) ([]*User, error) { func (c *Client) ListMyFollowers(opt ListFollowersOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?%s", opt.getURLQuery().Encode()), nil, nil, &users) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/followers?%s", opt.getURLQuery().Encode()), nil, nil, &users)
return users, resp, err
} }
// ListFollowers list all the followers of one user // ListFollowers list all the followers of one user
func (c *Client) ListFollowers(user string, opt ListFollowersOptions) ([]*User, error) { func (c *Client) ListFollowers(user string, opt ListFollowersOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?%s", user, opt.getURLQuery().Encode()), nil, nil, &users) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?%s", user, opt.getURLQuery().Encode()), nil, nil, &users)
return users, resp, err
} }
// ListFollowingOptions options for listing a user's users being followed // ListFollowingOptions options for listing a user's users being followed
@ -31,39 +33,41 @@ type ListFollowingOptions struct {
} }
// ListMyFollowing list all the users current user followed // ListMyFollowing list all the users current user followed
func (c *Client) ListMyFollowing(opt ListFollowingOptions) ([]*User, error) { func (c *Client) ListMyFollowing(opt ListFollowingOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?%s", opt.getURLQuery().Encode()), nil, nil, &users) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/following?%s", opt.getURLQuery().Encode()), nil, nil, &users)
return users, resp, err
} }
// ListFollowing list all the users the user followed // ListFollowing list all the users the user followed
func (c *Client) ListFollowing(user string, opt ListFollowingOptions) ([]*User, error) { func (c *Client) ListFollowing(user string, opt ListFollowingOptions) ([]*User, *Response, error) {
opt.setDefaults() opt.setDefaults()
users := make([]*User, 0, opt.PageSize) users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?%s", user, opt.getURLQuery().Encode()), nil, nil, &users) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?%s", user, opt.getURLQuery().Encode()), nil, nil, &users)
return users, resp, err
} }
// IsFollowing if current user followed the target // IsFollowing if current user followed the target
func (c *Client) IsFollowing(target string) bool { func (c *Client) IsFollowing(target string) (bool, *Response) {
_, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil) _, resp, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err == nil return err == nil, resp
} }
// IsUserFollowing if the user followed the target // IsUserFollowing if the user followed the target
func (c *Client) IsUserFollowing(user, target string) bool { func (c *Client) IsUserFollowing(user, target string) (bool, *Response) {
_, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil) _, resp, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil)
return err == nil return err == nil, resp
} }
// Follow set current user follow the target // Follow set current user follow the target
func (c *Client) Follow(target string) error { func (c *Client) Follow(target string) (*Response, error) {
_, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil) _, resp, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err return resp, err
} }
// Unfollow set current user unfollow the target // Unfollow set current user unfollow the target
func (c *Client) Unfollow(target string) error { func (c *Client) Unfollow(target string) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err return resp, err
} }

View File

@ -39,23 +39,26 @@ type ListGPGKeysOptions struct {
} }
// ListGPGKeys list all the GPG keys of the user // ListGPGKeys list all the GPG keys of the user
func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, error) { func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, *Response, error) {
opt.setDefaults() opt.setDefaults()
keys := make([]*GPGKey, 0, opt.PageSize) keys := make([]*GPGKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} }
// ListMyGPGKeys list all the GPG keys of current user // ListMyGPGKeys list all the GPG keys of current user
func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, error) { func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, *Response, error) {
opt.setDefaults() opt.setDefaults()
keys := make([]*GPGKey, 0, opt.PageSize) keys := make([]*GPGKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} }
// GetGPGKey get current user's GPG key by key id // GetGPGKey get current user's GPG key by key id
func (c *Client) GetGPGKey(keyID int64) (*GPGKey, error) { func (c *Client) GetGPGKey(keyID int64) (*GPGKey, *Response, error) {
key := new(GPGKey) key := new(GPGKey)
return key, c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil, &key) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil, &key)
return key, resp, err
} }
// CreateGPGKeyOption options create user GPG key // CreateGPGKeyOption options create user GPG key
@ -66,17 +69,18 @@ type CreateGPGKeyOption struct {
} }
// CreateGPGKey create GPG key with options // CreateGPGKey create GPG key with options
func (c *Client) CreateGPGKey(opt CreateGPGKeyOption) (*GPGKey, error) { func (c *Client) CreateGPGKey(opt CreateGPGKeyOption) (*GPGKey, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
key := new(GPGKey) key := new(GPGKey)
return key, c.getParsedResponse("POST", "/user/gpg_keys", jsonHeader, bytes.NewReader(body), key) resp, err := c.getParsedResponse("POST", "/user/gpg_keys", jsonHeader, bytes.NewReader(body), key)
return key, resp, err
} }
// DeleteGPGKey delete GPG key with key id // DeleteGPGKey delete GPG key with key id
func (c *Client) DeleteGPGKey(keyID int64) error { func (c *Client) DeleteGPGKey(keyID int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil)
return err return resp, err
} }

View File

@ -30,23 +30,26 @@ type ListPublicKeysOptions struct {
} }
// ListPublicKeys list all the public keys of the user // ListPublicKeys list all the public keys of the user
func (c *Client) ListPublicKeys(user string, opt ListPublicKeysOptions) ([]*PublicKey, error) { func (c *Client) ListPublicKeys(user string, opt ListPublicKeysOptions) ([]*PublicKey, *Response, error) {
opt.setDefaults() opt.setDefaults()
keys := make([]*PublicKey, 0, opt.PageSize) keys := make([]*PublicKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} }
// ListMyPublicKeys list all the public keys of current user // ListMyPublicKeys list all the public keys of current user
func (c *Client) ListMyPublicKeys(opt ListPublicKeysOptions) ([]*PublicKey, error) { func (c *Client) ListMyPublicKeys(opt ListPublicKeysOptions) ([]*PublicKey, *Response, error) {
opt.setDefaults() opt.setDefaults()
keys := make([]*PublicKey, 0, opt.PageSize) keys := make([]*PublicKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/user/keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys)
return keys, resp, err
} }
// GetPublicKey get current user's public key by key id // GetPublicKey get current user's public key by key id
func (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) { func (c *Client) GetPublicKey(keyID int64) (*PublicKey, *Response, error) {
key := new(PublicKey) key := new(PublicKey)
return key, c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key)
return key, resp, err
} }
// CreateKeyOption options when creating a key // CreateKeyOption options when creating a key
@ -60,17 +63,18 @@ type CreateKeyOption struct {
} }
// CreatePublicKey create public key with options // CreatePublicKey create public key with options
func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) { func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, *Response, error) {
body, err := json.Marshal(&opt) body, err := json.Marshal(&opt)
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
key := new(PublicKey) key := new(PublicKey)
return key, c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key) resp, err := c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key)
return key, resp, err
} }
// DeletePublicKey delete public key with key id // DeletePublicKey delete public key with key id
func (c *Client) DeletePublicKey(keyID int64) error { func (c *Client) DeletePublicKey(keyID int64) (*Response, error) {
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil) _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil)
return err return resp, err
} }

View File

@ -35,10 +35,10 @@ func (opt *SearchUsersOption) QueryEncode() string {
} }
// SearchUsers finds users by query // SearchUsers finds users by query
func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, error) { func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, *Response, error) {
link, _ := url.Parse("/users/search") link, _ := url.Parse("/users/search")
link.RawQuery = opt.QueryEncode() link.RawQuery = opt.QueryEncode()
resp := new(searchUsersResponse) userResp := new(searchUsersResponse)
err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &userResp)
return resp.Users, err return userResp.Users, resp, err
} }

View File

@ -11,11 +11,12 @@ import (
) )
// ServerVersion returns the version of the server // ServerVersion returns the version of the server
func (c *Client) ServerVersion() (string, error) { func (c *Client) ServerVersion() (string, *Response, error) {
var v = struct { var v = struct {
Version string `json:"version"` Version string `json:"version"`
}{} }{}
return v.Version, c.getParsedResponse("GET", "/version", nil, nil, &v) resp, err := c.getParsedResponse("GET", "/version", nil, nil, &v)
return v.Version, resp, err
} }
// CheckServerVersionConstraint validates that the login's server satisfies a // CheckServerVersionConstraint validates that the login's server satisfies a
@ -46,7 +47,7 @@ func (c *Client) loadClientServerVersion() error {
c.versionLock.Lock() c.versionLock.Lock()
defer c.versionLock.Unlock() defer c.versionLock.Unlock()
raw, err := c.ServerVersion() raw, _, err := c.ServerVersion()
if err != nil { if err != nil {
return err return err
} }

2
vendor/modules.txt vendored
View File

@ -1,7 +1,7 @@
# code.gitea.io/gitea-vet v0.2.0 # code.gitea.io/gitea-vet v0.2.0
code.gitea.io/gitea-vet code.gitea.io/gitea-vet
code.gitea.io/gitea-vet/checks code.gitea.io/gitea-vet/checks
# code.gitea.io/sdk/gitea v0.12.1 # code.gitea.io/sdk/gitea v0.13.0
code.gitea.io/sdk/gitea code.gitea.io/sdk/gitea
# github.com/araddon/dateparse v0.0.0-20200409225146-d820a6159ab1 # github.com/araddon/dateparse v0.0.0-20200409225146-d820a6159ab1
github.com/araddon/dateparse github.com/araddon/dateparse