Migrate gitea-sdk to v0.12.0 (#133)

Migrate

Update code.gitea.io/sdk/gitea to v0.12.0.

Co-authored-by: 6543 <6543@obermui.de>
Reviewed-on: https://gitea.com/gitea/tea/pulls/133
Reviewed-by: Andrew Thornton <art27@cantab.net>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
6543 2020-05-27 13:48:09 +00:00 committed by Lunny Xiao
parent 3c312cb409
commit 59fe58577a
50 changed files with 1625 additions and 308 deletions

View File

@ -87,8 +87,7 @@ func runIssuesList(ctx *cli.Context) error {
}
issues, err := login.Client().ListRepoIssues(owner, repo, gitea.ListIssueOption{
Page: 0,
State: string(state),
State: state,
Type: gitea.IssueTypeIssue,
})
@ -182,7 +181,7 @@ var CmdIssuesReopen = cli.Command{
Description: `Change state of an issue to 'open'`,
ArgsUsage: "<issue index>",
Action: func(ctx *cli.Context) error {
var s = string(gitea.StateOpen)
var s = gitea.StateOpen
return editIssueState(ctx, gitea.EditIssueOption{State: &s})
},
Flags: AllDefaultFlags,
@ -195,7 +194,7 @@ var CmdIssuesClose = cli.Command{
Description: `Change state of an issue to 'closed'`,
ArgsUsage: "<issue index>",
Action: func(ctx *cli.Context) error {
var s = string(gitea.StateClosed)
var s = gitea.StateClosed
return editIssueState(ctx, gitea.EditIssueOption{State: &s})
},
Flags: AllDefaultFlags,

View File

@ -49,7 +49,7 @@ func runLabels(ctx *cli.Context) error {
var values [][]string
labels, err := login.Client().ListRepoLabels(owner, repo)
labels, err := login.Client().ListRepoLabels(owner, repo, gitea.ListLabelsOptions{})
if err != nil {
log.Fatal(err)
}

View File

@ -52,8 +52,7 @@ func runPulls(ctx *cli.Context) error {
}
prs, err := login.Client().ListRepoPullRequests(owner, repo, gitea.ListPullRequestsOptions{
Page: 0,
State: string(state),
State: state,
})
if err != nil {

View File

@ -29,7 +29,7 @@ var CmdReleases = cli.Command{
func runReleases(ctx *cli.Context) error {
login, owner, repo := initCommand()
releases, err := login.Client().ListReleases(owner, repo)
releases, err := login.Client().ListReleases(owner, repo, gitea.ListReleasesOptions{})
if err != nil {
log.Fatal(err)
}

View File

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

View File

@ -73,7 +73,7 @@ func runTrackedTimes(ctx *cli.Context) error {
if err != nil {
return err
}
times, err = client.ListTrackedTimes(owner, repo, issue)
times, err = client.ListTrackedTimes(owner, repo, issue, gitea.ListTrackedTimesOptions{})
} else {
// get all tracked times by the specified user
times, err = client.GetUserTrackedTimes(owner, repo, user)

2
go.mod
View File

@ -3,7 +3,7 @@ module code.gitea.io/tea
go 1.12
require (
code.gitea.io/sdk/gitea v0.11.3
code.gitea.io/sdk/gitea v0.12.0
gitea.com/jolheiser/gitea-vet v0.1.0
github.com/araddon/dateparse v0.0.0-20200409225146-d820a6159ab1
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect

4
go.sum
View File

@ -1,5 +1,5 @@
code.gitea.io/sdk/gitea v0.11.3 h1:CdI3J82Mqn0mElyEKa5DUSr3Wi2R+qm/6uVtCkSSqSM=
code.gitea.io/sdk/gitea v0.11.3/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY=
code.gitea.io/sdk/gitea v0.12.0 h1:hvDCz4wtFvo7rf5Ebj8tGd4aJ4wLPKX3BKFX9Dk1Pgs=
code.gitea.io/sdk/gitea v0.12.0/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY=
gitea.com/jolheiser/gitea-vet v0.1.0 h1:gJEms9YWbIcrPOEmDOJ+5JZXCYFxNpwxlI73uRulAi4=
gitea.com/jolheiser/gitea-vet v0.1.0/go.mod h1:2Oa6TAdEp1N/38oBNh3ZeiSEER60D/CeDaBFv2sdH58=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=

View File

@ -11,10 +11,16 @@ import (
"fmt"
)
// AdminListOrgsOptions options for listing admin's organizations
type AdminListOrgsOptions struct {
ListOptions
}
// AdminListOrgs lists all orgs
func (c *Client) AdminListOrgs() ([]*Organization, error) {
orgs := make([]*Organization, 0, 10)
return orgs, c.getParsedResponse("GET", "/admin/orgs", nil, nil, &orgs)
func (c *Client) AdminListOrgs(opt AdminListOrgsOptions) ([]*Organization, error) {
opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/admin/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs)
}
// AdminCreateOrg create an organization

View File

@ -11,10 +11,16 @@ import (
"fmt"
)
// AdminListUsersOptions options for listing admin users
type AdminListUsersOptions struct {
ListOptions
}
// AdminListUsers lists all users
func (c *Client) AdminListUsers() ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", "/admin/users", nil, nil, &users)
func (c *Client) AdminListUsers(opt AdminListUsersOptions) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/admin/users?%s", opt.getURLQuery().Encode()), nil, nil, &users)
}
// CreateUserOption create user options

View File

@ -24,11 +24,17 @@ type Attachment struct {
DownloadURL string `json:"browser_download_url"`
}
// ListReleaseAttachmentsOptions options for listing release's attachments
type ListReleaseAttachmentsOptions struct {
ListOptions
}
// ListReleaseAttachments list release's attachments
func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10)
func (c *Client) ListReleaseAttachments(user, repo string, release int64, opt ListReleaseAttachmentsOptions) ([]*Attachment, error) {
opt.setDefaults()
attachments := make([]*Attachment, 0, opt.PageSize)
err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release),
fmt.Sprintf("/repos/%s/%s/releases/%d/assets?%s", user, repo, release, opt.getURLQuery().Encode()),
nil, nil, &attachments)
return attachments, err
}

View File

@ -22,7 +22,7 @@ var jsonHeader = http.Header{"content-type": []string{"application/json"}}
// Version return the library version
func Version() string {
return "0.11.1"
return "0.12.0"
}
// Client represents a Gitea API client.
@ -31,6 +31,7 @@ type Client struct {
accessToken string
username string
password string
otp string
sudo string
client *http.Client
serverVersion *version.Version
@ -58,6 +59,11 @@ func (c *Client) SetBasicAuth(username, password string) {
c.username, c.password = username, password
}
// SetOTP sets OTP for 2FA
func (c *Client) SetOTP(otp string) {
c.otp = otp
}
// SetHTTPClient replaces default http.Client with user given one.
func (c *Client) SetHTTPClient(client *http.Client) {
c.client = client
@ -76,10 +82,13 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read
if len(c.accessToken) != 0 {
req.Header.Set("Authorization", "token "+c.accessToken)
}
if len(c.otp) != 0 {
req.Header.Set("X-GITEA-OTP", c.otp)
}
if len(c.username) != 0 {
req.SetBasicAuth(c.username, c.password)
}
if c.sudo != "" {
if len(c.sudo) != 0 {
req.Header.Set("Sudo", c.sudo)
}
for k, v := range header {

View File

@ -10,13 +10,18 @@ import (
"fmt"
)
// ListForksOptions options for listing repository's forks
type ListForksOptions struct {
ListOptions
}
// ListForks list a repository's forks
func (c *Client) ListForks(user, repo string) ([]*Repository, error) {
forks := make([]*Repository, 10)
err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/forks", user, repo),
func (c *Client) ListForks(user string, repo string, opt ListForksOptions) ([]*Repository, error) {
opt.setDefaults()
forks := make([]*Repository, opt.PageSize)
return forks, c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/forks?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &forks)
return forks, err
}
// CreateForkOption options for creating a fork
@ -32,8 +37,5 @@ func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Reposito
return nil, err
}
fork := new(Repository)
err = c.getParsedResponse("POST",
fmt.Sprintf("/repos/%s/%s/forks", user, repo),
jsonHeader, bytes.NewReader(body), &fork)
return fork, err
return fork, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork)
}

View File

@ -17,10 +17,16 @@ type GitHook struct {
Content string `json:"content,omitempty"`
}
// ListRepoGitHooksOptions options for listing repository's githooks
type ListRepoGitHooksOptions struct {
ListOptions
}
// ListRepoGitHooks list all the Git hooks of one repository
func (c *Client) ListRepoGitHooks(user, repo string) ([]*GitHook, error) {
hooks := make([]*GitHook, 0, 10)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git", user, repo), nil, nil, &hooks)
func (c *Client) ListRepoGitHooks(user, repo string, opt ListRepoGitHooksOptions) ([]*GitHook, error) {
opt.setDefaults()
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)
}
// GetRepoGitHook get a Git hook of a repository

View File

@ -24,16 +24,23 @@ type Hook struct {
Created time.Time `json:"created_at"`
}
// ListHooksOptions options for listing hooks
type ListHooksOptions struct {
ListOptions
}
// ListOrgHooks list all the hooks of one organization
func (c *Client) ListOrgHooks(org string) ([]*Hook, error) {
hooks := make([]*Hook, 0, 10)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks", org), nil, nil, &hooks)
func (c *Client) ListOrgHooks(org string, opt ListHooksOptions) ([]*Hook, error) {
opt.setDefaults()
hooks := make([]*Hook, 0, opt.PageSize)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks?%s", org, opt.getURLQuery().Encode()), nil, nil, &hooks)
}
// ListRepoHooks list all the hooks of one repository
func (c *Client) ListRepoHooks(user, repo string) ([]*Hook, error) {
hooks := make([]*Hook, 0, 10)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), nil, nil, &hooks)
func (c *Client) ListRepoHooks(user, repo string, opt ListHooksOptions) ([]*Hook, error) {
opt.setDefaults()
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)
}
// GetOrgHook get a hook of an organization

View File

@ -10,6 +10,7 @@ import (
"encoding/json"
"fmt"
"net/url"
"strings"
"time"
)
@ -19,6 +20,14 @@ type PullRequestMeta struct {
Merged *time.Time `json:"merged_at"`
}
// RepositoryMeta basic repository information
type RepositoryMeta struct {
ID int64 `json:"id"`
Name string `json:"name"`
Owner string `json:"owner"`
FullName string `json:"full_name"`
}
// Issue represents an issue in a repository
type Issue struct {
ID int64 `json:"id"`
@ -41,18 +50,31 @@ type Issue struct {
Closed *time.Time `json:"closed_at"`
Deadline *time.Time `json:"due_date"`
PullRequest *PullRequestMeta `json:"pull_request"`
Repository *RepositoryMeta `json:"repository"`
}
// ListIssueOption list issue options
type ListIssueOption struct {
Page int
// open, closed, all
State string
ListOptions
State StateType
Type IssueType
Labels []string
Milestones []string
KeyWord string
}
// StateType issue state type
type StateType string
const (
// StateOpen pr/issue is opend
StateOpen StateType = "open"
// StateClosed pr/issue is closed
StateClosed StateType = "closed"
// StateAll is all
StateAll StateType = "all"
)
// IssueType is issue a pull or only an issue
type IssueType string
@ -67,79 +89,73 @@ const (
// QueryEncode turns options into querystring argument
func (opt *ListIssueOption) QueryEncode() string {
query := make(url.Values)
if opt.Page > 0 {
query.Add("page", fmt.Sprintf("%d", opt.Page))
}
query := opt.getURLQuery()
if len(opt.State) > 0 {
query.Add("state", opt.State)
query.Add("state", string(opt.State))
}
if opt.Page > 0 {
query.Add("page", fmt.Sprintf("%d", opt.Page))
}
if len(opt.State) > 0 {
query.Add("state", opt.State)
}
if len(opt.Labels) > 0 {
var lq string
for _, l := range opt.Labels {
if len(lq) > 0 {
lq += ","
}
lq += l
}
query.Add("labels", lq)
query.Add("labels", strings.Join(opt.Labels, ","))
}
if len(opt.KeyWord) > 0 {
query.Add("q", opt.KeyWord)
}
query.Add("type", string(opt.Type))
if len(opt.Milestones) > 0 {
query.Add("milestones", strings.Join(opt.Milestones, ","))
}
return query.Encode()
}
// ListIssues returns all issues assigned the authenticated user
func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) {
link, _ := url.Parse("/repos/issues/search")
issues := make([]*Issue, 0, 10)
link.RawQuery = opt.QueryEncode()
return issues, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
}
opt.setDefaults()
issues := make([]*Issue, 0, opt.PageSize)
// ListUserIssues returns all issues assigned to the authenticated user
func (c *Client) ListUserIssues(opt ListIssueOption) ([]*Issue, error) {
// WARNING: "/user/issues" API is not implemented jet!
allIssues, err := c.ListIssues(opt)
if err != nil {
return nil, err
}
user, err := c.GetMyUserInfo()
if err != nil {
return nil, err
}
// Workaround: client sort out non user related issues
issues := make([]*Issue, 0, 10)
for _, i := range allIssues {
if i.ID == user.ID {
issues = append(issues, i)
link, _ := url.Parse("/repos/issues/search")
link.RawQuery = opt.QueryEncode()
err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
for i := 0; i < len(issues); i++ {
if issues[i].Repository != nil {
issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0]
}
}
return issues, nil
}
return issues, err
}
// ListRepoIssues returns all issues for a given repository
func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) {
opt.setDefaults()
issues := make([]*Issue, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues", owner, repo))
issues := make([]*Issue, 0, 10)
link.RawQuery = opt.QueryEncode()
return issues, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues)
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
for i := 0; i < len(issues); i++ {
if issues[i].Repository != nil {
issues[i].Repository.Owner = strings.Split(issues[i].Repository.FullName, "/")[0]
}
}
}
return issues, err
}
// GetIssue returns a single issue for a given repository
func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) {
issue := new(Issue)
return issue, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue)
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 {
issue.Repository.Owner = strings.Split(issue.Repository.FullName, "/")[0]
}
return issue, err
}
// CreateIssueOption options to create one issue
@ -175,7 +191,7 @@ type EditIssueOption struct {
Assignee *string `json:"assignee"`
Assignees []string `json:"assignees"`
Milestone *int64 `json:"milestone"`
State *string `json:"state"`
State *StateType `json:"state"`
Deadline *time.Time `json:"due_date"`
}

View File

@ -8,6 +8,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"time"
)
@ -25,16 +26,50 @@ type Comment struct {
Updated time.Time `json:"updated_at"`
}
// ListIssueCommentOptions list comment options
type ListIssueCommentOptions struct {
ListOptions
Since time.Time
Before time.Time
}
// QueryEncode turns options into querystring argument
func (opt *ListIssueCommentOptions) QueryEncode() string {
query := opt.getURLQuery()
if !opt.Since.IsZero() {
query.Add("since", opt.Since.Format(time.RFC3339))
}
if !opt.Before.IsZero() {
query.Add("before", opt.Before.Format(time.RFC3339))
}
return query.Encode()
}
// ListIssueComments list comments on an issue.
func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, error) {
comments := make([]*Comment, 0, 10)
return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments)
func (c *Client) ListIssueComments(owner, repo string, index int64, opt ListIssueCommentOptions) ([]*Comment, error) {
opt.setDefaults()
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index))
link.RawQuery = opt.QueryEncode()
comments := make([]*Comment, 0, opt.PageSize)
return comments, c.getParsedResponse("GET", link.String(), nil, nil, &comments)
}
// ListRepoIssueComments list comments for a given repo.
func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) {
comments := make([]*Comment, 0, 10)
return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments)
func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentOptions) ([]*Comment, error) {
opt.setDefaults()
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo))
link.RawQuery = opt.QueryEncode()
comments := make([]*Comment, 0, opt.PageSize)
return comments, c.getParsedResponse("GET", link.String(), nil, nil, &comments)
}
// GetIssueComment get a comment for a given repo by id.
func (c *Client) GetIssueComment(owner, repo string, id int64) (*Comment, error) {
comment := new(Comment)
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return comment, err
}
return comment, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, id), nil, nil, &comment)
}
// CreateIssueCommentOption options for creating a comment on an issue

View File

@ -20,10 +20,16 @@ type Label struct {
URL string `json:"url"`
}
// ListLabelsOptions options for listing repository's labels
type ListLabelsOptions struct {
ListOptions
}
// ListRepoLabels list labels of one repository
func (c *Client) ListRepoLabels(owner, repo string) ([]*Label, error) {
labels := make([]*Label, 0, 10)
return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), nil, nil, &labels)
func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*Label, error) {
opt.setDefaults()
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)
}
// GetRepoLabel get one label of repository by repo it
@ -77,9 +83,9 @@ func (c *Client) DeleteLabel(owner, repo string, id int64) error {
}
// GetIssueLabels get labels of one issue via issue id
func (c *Client) GetIssueLabels(owner, repo string, index int64) ([]*Label, error) {
func (c *Client) GetIssueLabels(owner, repo string, index int64, opts ListLabelsOptions) ([]*Label, error) {
labels := make([]*Label, 0, 5)
return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil, &labels)
return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels)
}
// IssueLabelsOption a collection of labels

View File

@ -8,21 +8,10 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"time"
)
// StateType issue state type
type StateType string
const (
// StateOpen pr is opend
StateOpen StateType = "open"
// StateClosed pr is closed
StateClosed StateType = "closed"
// StateAll is all
StateAll StateType = "all"
)
// Milestone milestone is a collection of issues on one repository
type Milestone struct {
ID int64 `json:"id"`
@ -35,10 +24,30 @@ type Milestone struct {
Deadline *time.Time `json:"due_on"`
}
// ListMilestoneOption list milestone options
type ListMilestoneOption struct {
ListOptions
// open, closed, all
State StateType
}
// QueryEncode turns options into querystring argument
func (opt *ListMilestoneOption) QueryEncode() string {
query := opt.getURLQuery()
if opt.State != "" {
query.Add("state", string(opt.State))
}
return query.Encode()
}
// ListRepoMilestones list all the milestones of one repository
func (c *Client) ListRepoMilestones(owner, repo string) ([]*Milestone, error) {
milestones := make([]*Milestone, 0, 10)
return milestones, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), nil, nil, &milestones)
func (c *Client) ListRepoMilestones(owner, repo string, opt ListMilestoneOption) ([]*Milestone, error) {
opt.setDefaults()
milestones := make([]*Milestone, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/milestones", owner, repo))
link.RawQuery = opt.QueryEncode()
return milestones, c.getParsedResponse("GET", link.String(), nil, nil, &milestones)
}
// GetMilestone get one milestone by repo name and milestone id

View File

@ -6,6 +6,7 @@ package gitea
import (
"fmt"
"net/http"
)
// GetIssueSubscribers get list of users who subscribed on an issue
@ -22,8 +23,17 @@ func (c *Client) AddIssueSubscription(owner, repo string, index int64, user stri
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err
}
_, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
status, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
if err != nil {
return err
}
if status == http.StatusCreated {
return nil
}
if status == http.StatusOK {
return fmt.Errorf("already subscribed")
}
return fmt.Errorf("unexpected Status: %d", status)
}
// DeleteIssueSubscription unsubscribe user from issue
@ -31,8 +41,26 @@ func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user s
if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil {
return err
}
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil)
if err != nil {
return err
}
if status == http.StatusCreated {
return nil
}
if status == http.StatusOK {
return fmt.Errorf("already unsubscribed")
}
return fmt.Errorf("unexpected Status: %d", status)
}
// CheckIssueSubscription check if current user is subscribed to an issue
func (c *Client) CheckIssueSubscription(owner, repo string, index int64) (*WatchInfo, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
wi := new(WatchInfo)
return wi, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/check", owner, repo, index), nil, nil, wi)
}
// IssueSubscribe subscribe current user to an issue

View File

@ -37,12 +37,6 @@ func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, error)
return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, &times)
}
// ListTrackedTimes list tracked times of a single issue for a given repository
func (c *Client) ListTrackedTimes(owner, repo string, index int64) ([]*TrackedTime, error) {
times := make([]*TrackedTime, 0, 10)
return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil, &times)
}
// GetMyTrackedTimes list tracked times of the current user
func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, error) {
times := make([]*TrackedTime, 0, 10)
@ -70,6 +64,18 @@ func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*T
jsonHeader, bytes.NewReader(body), t)
}
// ListTrackedTimesOptions options for listing repository's tracked times
type ListTrackedTimesOptions struct {
ListOptions
}
// 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) {
opt.setDefaults()
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)
}
// ResetIssueTime reset tracked time of a single issue for a given repository
func (c *Client) ResetIssueTime(owner, repo string, index int64) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil)

37
vendor/code.gitea.io/sdk/gitea/list_options.go generated vendored Normal file
View File

@ -0,0 +1,37 @@
// 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"
"net/url"
)
const defaultPageSize = 10
const maxPageSize = 50
// ListOptions options for using Gitea's API pagination
type ListOptions struct {
Page int
PageSize int
}
func (o ListOptions) getURLQuery() url.Values {
query := make(url.Values)
query.Add("page", fmt.Sprintf("%d", o.Page))
query.Add("limit", fmt.Sprintf("%d", o.PageSize))
return query
}
func (o ListOptions) setDefaults() {
if o.Page < 1 {
o.Page = 1
}
if o.PageSize < 0 || o.PageSize > maxPageSize {
o.PageSize = defaultPageSize
}
}

137
vendor/code.gitea.io/sdk/gitea/notifications.go generated vendored Normal file
View File

@ -0,0 +1,137 @@
// 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"
"net/url"
"time"
)
// NotificationThread expose Notification on API
type NotificationThread struct {
ID int64 `json:"id"`
Repository *Repository `json:"repository"`
Subject *NotificationSubject `json:"subject"`
Unread bool `json:"unread"`
Pinned bool `json:"pinned"`
UpdatedAt time.Time `json:"updated_at"`
URL string `json:"url"`
}
// NotificationSubject contains the notification subject (Issue/Pull/Commit)
type NotificationSubject struct {
Title string `json:"title"`
URL string `json:"url"`
LatestCommentURL string `json:"latest_comment_url"`
Type string `json:"type" binding:"In(Issue,Pull,Commit)"`
}
// ListNotificationOptions represents the filter options
type ListNotificationOptions struct {
ListOptions
Since time.Time
Before time.Time
}
// MarkNotificationOptions represents the filter options
type MarkNotificationOptions struct {
LastReadAt time.Time
}
// QueryEncode encode options to url query
func (opt *ListNotificationOptions) QueryEncode() string {
query := opt.getURLQuery()
if !opt.Since.IsZero() {
query.Add("since", opt.Since.Format(time.RFC3339))
}
if !opt.Before.IsZero() {
query.Add("before", opt.Before.Format(time.RFC3339))
}
return query.Encode()
}
// QueryEncode encode options to url query
func (opt *MarkNotificationOptions) QueryEncode() string {
query := make(url.Values)
if !opt.LastReadAt.IsZero() {
query.Add("last_read_at", opt.LastReadAt.Format(time.RFC3339))
}
return query.Encode()
}
// CheckNotifications list users's notification threads
func (c *Client) CheckNotifications() (int64, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return 0, err
}
new := struct {
New int64 `json:"new"`
}{}
return new.New, c.getParsedResponse("GET", "/notifications/new", jsonHeader, nil, &new)
}
// GetNotification get notification thread by ID
func (c *Client) GetNotification(id int64) (*NotificationThread, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
thread := new(NotificationThread)
return thread, c.getParsedResponse("GET", fmt.Sprintf("/notifications/threads/%d", id), nil, nil, thread)
}
// ReadNotification mark notification thread as read by ID
func (c *Client) ReadNotification(id int64) error {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err
}
_, err := c.getResponse("PATCH", fmt.Sprintf("/notifications/threads/%d", id), nil, nil)
return err
}
// ListNotifications list users's notification threads
func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
link, _ := url.Parse("/notifications")
link.RawQuery = opt.QueryEncode()
threads := make([]*NotificationThread, 0, 10)
return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads)
}
// ReadNotifications mark notification threads as read
func (c *Client) ReadNotifications(opt MarkNotificationOptions) error {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err
}
link, _ := url.Parse("/notifications")
link.RawQuery = opt.QueryEncode()
_, err := c.getResponse("PUT", link.String(), nil, nil)
return err
}
// ListRepoNotifications list users's notification threads on a specific repo
func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame))
link.RawQuery = opt.QueryEncode()
threads := make([]*NotificationThread, 0, 10)
return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads)
}
// ReadRepoNotifications mark notification threads as read on a specific repo
func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) error {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err
}
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame))
link.RawQuery = opt.QueryEncode()
_, err := c.getResponse("PUT", link.String(), nil, nil)
return err
}

87
vendor/code.gitea.io/sdk/gitea/oauth2.go generated vendored Normal file
View File

@ -0,0 +1,87 @@
// 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"
"time"
)
// Oauth2 represents an Oauth2 Application
type Oauth2 struct {
ID int64 `json:"id"`
Name string `json:"name"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURIs []string `json:"redirect_uris"`
Created time.Time `json:"created"`
}
// ListOauth2Option for listing Oauth2 Applications
type ListOauth2Option struct {
ListOptions
}
// CreateOauth2Option required options for creating an Application
type CreateOauth2Option struct {
Name string `json:"name"`
RedirectURIs []string `json:"redirect_uris"`
}
// CreateOauth2 create an Oauth2 Application and returns a completed Oauth2 object.
func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
return nil, e
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
oauth := new(Oauth2)
return oauth, c.getParsedResponse("POST", "/user/applications/oauth2", jsonHeader, bytes.NewReader(body), oauth)
}
// UpdateOauth2 a specific Oauth2 Application by ID and return a completed Oauth2 object.
func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
return nil, e
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
oauth := new(Oauth2)
return oauth, c.getParsedResponse("PATCH", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), jsonHeader, bytes.NewReader(body), oauth)
}
// GetOauth2 a specific Oauth2 Application by ID.
func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
return nil, e
}
oauth2s := &Oauth2{}
return oauth2s, c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil, &oauth2s)
}
// ListOauth2 all of your Oauth2 Applications.
func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, error) {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
return nil, e
}
opt.setDefaults()
oauth2s := make([]*Oauth2, 0, opt.PageSize)
return oauth2s, c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2?%s", opt.getURLQuery().Encode()), nil, nil, &oauth2s)
}
// DeleteOauth2 delete an Oauth2 application by ID
func (c *Client) DeleteOauth2(oauth2id int64) error {
if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil {
return e
}
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil)
return err
}

View File

@ -23,16 +23,23 @@ type Organization struct {
Visibility string `json:"visibility"`
}
// ListOrgsOptions options for listing organizations
type ListOrgsOptions struct {
ListOptions
}
// ListMyOrgs list all of current user's organizations
func (c *Client) ListMyOrgs() ([]*Organization, error) {
orgs := make([]*Organization, 0, 5)
return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs)
func (c *Client) ListMyOrgs(opt ListOrgsOptions) ([]*Organization, error) {
opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/user/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs)
}
// ListUserOrgs list all of some user's organizations
func (c *Client) ListUserOrgs(user string) ([]*Organization, error) {
orgs := make([]*Organization, 0, 5)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs)
func (c *Client) ListUserOrgs(user string, opt ListOrgsOptions) ([]*Organization, error) {
opt.setDefaults()
orgs := make([]*Organization, 0, opt.PageSize)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs?%s", user, opt.getURLQuery().Encode()), nil, nil, &orgs)
}
// GetOrg get one organization by name

View File

@ -1,26 +1,98 @@
// Copyright 2016 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
// license that can be found in the LICENSE file.
package gitea
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// AddOrgMembershipOption add user to organization options
type AddOrgMembershipOption struct {
Role string `json:"role"`
// DeleteOrgMembership remove a member from an organization
func (c *Client) DeleteOrgMembership(org, user string) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
return err
}
// AddOrgMembership add some one to an organization's member
func (c *Client) AddOrgMembership(org, user string, opt AddOrgMembershipOption) error {
body, err := json.Marshal(&opt)
// ListOrgMembershipOption list OrgMembership options
type ListOrgMembershipOption struct {
ListOptions
}
// ListOrgMembership list an organization's members
func (c *Client) ListOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/orgs/%s/members", url.PathEscape(org)))
link.RawQuery = opt.getURLQuery().Encode()
return users, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users)
}
// ListPublicOrgMembership list an organization's members
func (c *Client) ListPublicOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/orgs/%s/public_members", url.PathEscape(org)))
link.RawQuery = opt.getURLQuery().Encode()
return users, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users)
}
// CheckOrgMembership Check if a user is a member of an organization
func (c *Client) CheckOrgMembership(org, user string) (bool, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
if err != nil {
return false, err
}
switch status {
case http.StatusNoContent:
return true, nil
case http.StatusNotFound:
return false, nil
default:
return false, fmt.Errorf("unexpected Status: %d", status)
}
}
// CheckPublicOrgMembership Check if a user is a member of an organization
func (c *Client) CheckPublicOrgMembership(org, user string) (bool, error) {
status, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
if err != nil {
return false, err
}
switch status {
case http.StatusNoContent:
return true, nil
case http.StatusNotFound:
return false, nil
default:
return false, fmt.Errorf("unexpected Status: %d", status)
}
}
// SetPublicOrgMembership publicize/conceal a user's membership
func (c *Client) SetPublicOrgMembership(org, user string, visible bool) error {
var (
status int
err error
)
if visible {
status, err = c.getStatusCode("PUT", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
} else {
status, err = c.getStatusCode("DELETE", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil)
}
if err != nil {
return err
}
_, err = c.getResponse("PUT", fmt.Sprintf("/orgs/%s/membership/%s", org, user), jsonHeader, bytes.NewReader(body))
return err
switch status {
case http.StatusNoContent:
return nil
case http.StatusNotFound:
return fmt.Errorf("forbidden")
default:
return fmt.Errorf("unexpected Status: %d", status)
}
}

View File

@ -22,16 +22,23 @@ type Team struct {
Units []string `json:"units"`
}
// ListTeamsOptions options for listing teams
type ListTeamsOptions struct {
ListOptions
}
// ListOrgTeams lists all teams of an organization
func (c *Client) ListOrgTeams(org string) ([]*Team, error) {
teams := make([]*Team, 0, 10)
return teams, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams", org), nil, nil, &teams)
func (c *Client) ListOrgTeams(org string, opt ListTeamsOptions) ([]*Team, error) {
opt.setDefaults()
teams := make([]*Team, 0, opt.PageSize)
return teams, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams?%s", org, opt.getURLQuery().Encode()), nil, nil, &teams)
}
// ListMyTeams lists all the teams of the current user
func (c *Client) ListMyTeams() ([]*Team, error) {
teams := make([]*Team, 0, 10)
return teams, c.getParsedResponse("GET", "/user/teams", nil, nil, &teams)
func (c *Client) ListMyTeams(opt *ListTeamsOptions) ([]*Team, error) {
opt.setDefaults()
teams := make([]*Team, 0, opt.PageSize)
return teams, c.getParsedResponse("GET", fmt.Sprintf("/user/teams?%s", opt.getURLQuery().Encode()), nil, nil, &teams)
}
// GetTeam gets a team by ID
@ -86,10 +93,16 @@ func (c *Client) DeleteTeam(id int64) error {
return err
}
// ListTeamMembersOptions options for listing team's members
type ListTeamMembersOptions struct {
ListOptions
}
// ListTeamMembers lists all members of a team
func (c *Client) ListTeamMembers(id int64) ([]*User, error) {
members := make([]*User, 0, 10)
return members, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members", id), nil, nil, &members)
func (c *Client) ListTeamMembers(id int64, opt ListTeamMembersOptions) ([]*User, error) {
opt.setDefaults()
members := make([]*User, 0, opt.PageSize)
return members, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members?%s", id, opt.getURLQuery().Encode()), nil, nil, &members)
}
// GetTeamMember gets a member of a team
@ -110,10 +123,16 @@ func (c *Client) RemoveTeamMember(id int64, user string) error {
return err
}
// ListTeamRepositoriesOptions options for listing team's repositories
type ListTeamRepositoriesOptions struct {
ListOptions
}
// ListTeamRepositories lists all repositories of a team
func (c *Client) ListTeamRepositories(id int64) ([]*Repository, error) {
repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos", id), nil, nil, &repos)
func (c *Client) ListTeamRepositories(id int64, opt ListTeamRepositoriesOptions) ([]*Repository, error) {
opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos?%s", id, opt.getURLQuery().Encode()), nil, nil, &repos)
}
// AddTeamRepository adds a repository to a team

View File

@ -59,26 +59,32 @@ type PullRequest struct {
// ListPullRequestsOptions options for listing pull requests
type ListPullRequestsOptions struct {
Page int `json:"page"`
// open, closed, all
State string `json:"state"`
ListOptions
State StateType `json:"state"`
// oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority
Sort string `json:"sort"`
Milestone int64 `json:"milestone"`
Sort string
Milestone int64
}
// ListRepoPullRequests list PRs of one repository
func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) {
// declare variables
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls", owner, repo))
prs := make([]*PullRequest, 0, 10)
query := make(url.Values)
// add options to query
if opt.Page > 0 {
query.Add("page", fmt.Sprintf("%d", opt.Page))
}
// MergeStyle is used specify how a pull is merged
type MergeStyle string
const (
// MergeStyleMerge merge pull as usual
MergeStyleMerge MergeStyle = "merge"
// MergeStyleRebase rebase pull
MergeStyleRebase MergeStyle = "rebase"
// MergeStyleRebaseMerge rebase and merge pull
MergeStyleRebaseMerge MergeStyle = "rebase-merge"
// MergeStyleSquash squash and merge pull
MergeStyleSquash MergeStyle = "squash"
)
// QueryEncode turns options into querystring argument
func (opt *ListPullRequestsOptions) QueryEncode() string {
query := opt.getURLQuery()
if len(opt.State) > 0 {
query.Add("state", opt.State)
query.Add("state", string(opt.State))
}
if len(opt.Sort) > 0 {
query.Add("sort", opt.Sort)
@ -86,8 +92,16 @@ func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOp
if opt.Milestone > 0 {
query.Add("milestone", fmt.Sprintf("%d", opt.Milestone))
}
link.RawQuery = query.Encode()
// request
return query.Encode()
}
// ListRepoPullRequests list PRs of one repository
func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) {
opt.setDefaults()
prs := make([]*PullRequest, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls", owner, repo))
link.RawQuery = opt.QueryEncode()
return prs, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &prs)
}
@ -129,7 +143,7 @@ type EditPullRequestOption struct {
Assignees []string `json:"assignees"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
State *string `json:"state"`
State *StateType `json:"state"`
Deadline *time.Time `json:"due_date"`
}
@ -146,15 +160,18 @@ func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRe
// MergePullRequestOption options when merging a pull request
type MergePullRequestOption struct {
// required: true
// enum: merge,rebase,rebase-merge,squash
Do string `json:"Do" binding:"Required;In(merge,rebase,rebase-merge,squash)"`
MergeTitleField string `json:"MergeTitleField"`
MergeMessageField string `json:"MergeMessageField"`
Style MergeStyle `json:"Do"`
Title string `json:"MergeTitleField"`
Message string `json:"MergeMessageField"`
}
// MergePullRequest merge a PR to repository by PR id
func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, error) {
if opt.Style == MergeStyleSquash {
if err := c.CheckServerVersionConstraint(">=1.11.5"); err != nil {
return false, err
}
}
body, err := json.Marshal(&opt)
if err != nil {
return false, err

184
vendor/code.gitea.io/sdk/gitea/pull_review.go generated vendored Normal file
View File

@ -0,0 +1,184 @@
// 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"
"net/url"
"time"
)
// ReviewStateType review state type
type ReviewStateType string
const (
// ReviewStateApproved pr is approved
ReviewStateApproved ReviewStateType = "APPROVED"
// ReviewStatePending pr state is pending
ReviewStatePending ReviewStateType = "PENDING"
// ReviewStateComment is a comment review
ReviewStateComment ReviewStateType = "COMMENT"
// ReviewStateRequestChanges changes for pr are requested
ReviewStateRequestChanges ReviewStateType = "REQUEST_CHANGES"
// ReviewStateRequestReview review is requested from user
ReviewStateRequestReview ReviewStateType = "REQUEST_REVIEW"
// ReviewStateUnknown state of pr is unknown
ReviewStateUnknown ReviewStateType = ""
)
// PullReview represents a pull request review
type PullReview struct {
ID int64 `json:"id"`
Reviewer *User `json:"user"`
State ReviewStateType `json:"state"`
Body string `json:"body"`
CommitID string `json:"commit_id"`
Stale bool `json:"stale"`
Official bool `json:"official"`
CodeCommentsCount int `json:"comments_count"`
// swagger:strfmt date-time
Submitted time.Time `json:"submitted_at"`
HTMLURL string `json:"html_url"`
HTMLPullURL string `json:"pull_request_url"`
}
// PullReviewComment represents a comment on a pull request review
type PullReviewComment struct {
ID int64 `json:"id"`
Body string `json:"body"`
Reviewer *User `json:"user"`
ReviewID int64 `json:"pull_request_review_id"`
// swagger:strfmt date-time
Created time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated time.Time `json:"updated_at"`
Path string `json:"path"`
CommitID string `json:"commit_id"`
OrigCommitID string `json:"original_commit_id"`
DiffHunk string `json:"diff_hunk"`
LineNum uint64 `json:"position"`
OldLineNum uint64 `json:"original_position"`
HTMLURL string `json:"html_url"`
HTMLPullURL string `json:"pull_request_url"`
}
// CreatePullReviewOptions are options to create a pull review
type CreatePullReviewOptions struct {
State ReviewStateType `json:"event"`
Body string `json:"body"`
CommitID string `json:"commit_id"`
Comments []CreatePullReviewComment `json:"comments"`
}
// CreatePullReviewComment represent a review comment for creation api
type CreatePullReviewComment struct {
// the tree path
Path string `json:"path"`
Body string `json:"body"`
// if comment to old file line or 0
OldLineNum int64 `json:"old_position"`
// if comment to new file line or 0
NewLineNum int64 `json:"new_position"`
}
// SubmitPullReviewOptions are options to submit a pending pull review
type SubmitPullReviewOptions struct {
State ReviewStateType `json:"event"`
Body string `json:"body"`
}
// ListPullReviewsOptions options for listing PullReviews
type ListPullReviewsOptions struct {
ListOptions
}
// ListPullReviews lists all reviews of a pull request
func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
opt.setDefaults()
rs := make([]*PullReview, 0, opt.PageSize)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index))
link.RawQuery = opt.ListOptions.getURLQuery().Encode()
return rs, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rs)
}
// GetPullReview gets a specific review of a pull request
func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
r := new(PullReview)
return r, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil, &r)
}
// ListPullReviewsCommentsOptions options for listing PullReviewsComments
type ListPullReviewsCommentsOptions struct {
ListOptions
}
// ListPullReviewComments lists all comments of a pull request review
func (c *Client) ListPullReviewComments(owner, repo string, index, id int64, opt ListPullReviewsCommentsOptions) ([]*PullReviewComment, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
opt.setDefaults()
rcl := make([]*PullReviewComment, 0, opt.PageSize)
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)
}
// DeletePullReview delete a specific review from a pull request
func (c *Client) DeletePullReview(owner, repo string, index, id int64) error {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err
}
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil)
return err
}
// CreatePullReview create a review to an pull request
func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePullReviewOptions) (*PullReview, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
r := new(PullReview)
return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index),
jsonHeader, bytes.NewReader(body), r)
}
// SubmitPullReview submit a pending review to an pull request
func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt SubmitPullReviewOptions) (*PullReview, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
r := new(PullReview)
return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id),
jsonHeader, bytes.NewReader(body), r)
}

View File

@ -29,11 +29,17 @@ type Release struct {
Attachments []*Attachment `json:"assets"`
}
// ListReleasesOptions options for listing repository's releases
type ListReleasesOptions struct {
ListOptions
}
// ListReleases list releases of a repository
func (c *Client) ListReleases(user, repo string) ([]*Release, error) {
releases := make([]*Release, 0, 10)
func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Release, error) {
opt.setDefaults()
releases := make([]*Release, 0, opt.PageSize)
err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/releases", user, repo),
fmt.Sprintf("/repos/%s/%s/releases?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &releases)
return releases, err
}

View File

@ -8,6 +8,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"time"
)
@ -56,22 +57,105 @@ type Repository struct {
AvatarURL string `json:"avatar_url"`
}
// ListReposOptions options for listing repositories
type ListReposOptions struct {
ListOptions
}
// ListMyRepos lists all repositories for the authenticated user that has access to.
func (c *Client) ListMyRepos() ([]*Repository, error) {
repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos)
func (c *Client) ListMyRepos(opt ListReposOptions) ([]*Repository, error) {
opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/user/repos?%s", opt.getURLQuery().Encode()), nil, nil, &repos)
}
// ListUserRepos list all repositories of one user by user's name
func (c *Client) ListUserRepos(user string) ([]*Repository, error) {
repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos", user), nil, nil, &repos)
func (c *Client) ListUserRepos(user string, opt ListReposOptions) ([]*Repository, error) {
opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos?%s", user, opt.getURLQuery().Encode()), nil, nil, &repos)
}
// ListOrgReposOptions options for a organization's repositories
type ListOrgReposOptions struct {
ListOptions
}
// ListOrgRepos list all repositories of one organization by organization's name
func (c *Client) ListOrgRepos(org string) ([]*Repository, error) {
repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos", org), nil, nil, &repos)
func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repository, error) {
opt.setDefaults()
repos := make([]*Repository, 0, opt.PageSize)
return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos?%s", org, opt.getURLQuery().Encode()), nil, nil, &repos)
}
// SearchRepoOptions options for searching repositories
type SearchRepoOptions struct {
ListOptions
Keyword string
Topic bool
IncludeDesc bool
UID int64
PriorityOwnerID int64
StarredBy int64
Private bool
Template bool
Mode string
Exclusive bool
Sort string
}
// QueryEncode turns options into querystring argument
func (opt *SearchRepoOptions) QueryEncode() string {
query := opt.getURLQuery()
if opt.Keyword != "" {
query.Add("q", opt.Keyword)
}
query.Add("topic", fmt.Sprintf("%t", opt.Topic))
query.Add("includeDesc", fmt.Sprintf("%t", opt.IncludeDesc))
if opt.UID > 0 {
query.Add("uid", fmt.Sprintf("%d", opt.UID))
}
if opt.PriorityOwnerID > 0 {
query.Add("priority_owner_id", fmt.Sprintf("%d", opt.PriorityOwnerID))
}
if opt.StarredBy > 0 {
query.Add("starredBy", fmt.Sprintf("%d", opt.StarredBy))
}
query.Add("private", fmt.Sprintf("%t", opt.Private))
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 != "" {
query.Add("sort", opt.Sort)
}
return query.Encode()
}
type searchRepoResponse struct {
Repos []*Repository `json:"data"`
}
// SearchRepos searches for repositories matching the given filters
func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) {
opt.setDefaults()
resp := new(searchRepoResponse)
link, _ := url.Parse("/repos/search")
link.RawQuery = opt.QueryEncode()
err := c.getParsedResponse("GET", link.String(), nil, nil, &resp)
return resp.Repos, err
}
// CreateRepoOption options when creating repository
@ -93,6 +177,8 @@ type CreateRepoOption struct {
License string `json:"license"`
// Readme of the repository to create
Readme string `json:"readme"`
// DefaultBranch of the repository (used when initializes and in template)
DefaultBranch string `json:"default_branch"`
}
// CreateRepo creates a repository for authenticated user.

View File

@ -1,4 +1,5 @@
// Copyright 2016 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
// license that can be found in the LICENSE file.
@ -47,16 +48,44 @@ type PayloadCommitVerification struct {
type Branch struct {
Name string `json:"name"`
Commit *PayloadCommit `json:"commit"`
Protected bool `json:"protected"`
RequiredApprovals int64 `json:"required_approvals"`
EnableStatusCheck bool `json:"enable_status_check"`
StatusCheckContexts []string `json:"status_check_contexts"`
UserCanPush bool `json:"user_can_push"`
UserCanMerge bool `json:"user_can_merge"`
EffectiveBranchProtectionName string `json:"effective_branch_protection_name"`
}
// ListRepoBranchesOptions options for listing a repository's branches
type ListRepoBranchesOptions struct {
ListOptions
}
// ListRepoBranches list all the branches of one repository
func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) {
branches := make([]*Branch, 0, 10)
return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches)
func (c *Client) ListRepoBranches(user, repo string, opt ListRepoBranchesOptions) ([]*Branch, error) {
opt.setDefaults()
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)
}
// GetRepoBranch get one branch's information of one repository
func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) {
b := new(Branch)
return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b)
if err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b); err != nil {
return nil, err
}
return b, nil
}
// DeleteRepoBranch delete a branch in a repository
func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return false, err
}
status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil)
if err != nil {
return false, err
}
return status == 204, nil
}

View File

@ -0,0 +1,148 @@
// 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"
"net/url"
"time"
)
// BranchProtection represents a branch protection for a repository
type BranchProtection struct {
BranchName string `json:"branch_name"`
EnablePush bool `json:"enable_push"`
EnablePushWhitelist bool `json:"enable_push_whitelist"`
PushWhitelistUsernames []string `json:"push_whitelist_usernames"`
PushWhitelistTeams []string `json:"push_whitelist_teams"`
PushWhitelistDeployKeys bool `json:"push_whitelist_deploy_keys"`
EnableMergeWhitelist bool `json:"enable_merge_whitelist"`
MergeWhitelistUsernames []string `json:"merge_whitelist_usernames"`
MergeWhitelistTeams []string `json:"merge_whitelist_teams"`
EnableStatusCheck bool `json:"enable_status_check"`
StatusCheckContexts []string `json:"status_check_contexts"`
RequiredApprovals int64 `json:"required_approvals"`
EnableApprovalsWhitelist bool `json:"enable_approvals_whitelist"`
ApprovalsWhitelistUsernames []string `json:"approvals_whitelist_username"`
ApprovalsWhitelistTeams []string `json:"approvals_whitelist_teams"`
BlockOnRejectedReviews bool `json:"block_on_rejected_reviews"`
BlockOnOutdatedBranch bool `json:"block_on_outdated_branch"`
DismissStaleApprovals bool `json:"dismiss_stale_approvals"`
RequireSignedCommits bool `json:"require_signed_commits"`
ProtectedFilePatterns string `json:"protected_file_patterns"`
// swagger:strfmt date-time
Created time.Time `json:"created_at"`
// swagger:strfmt date-time
Updated time.Time `json:"updated_at"`
}
// CreateBranchProtectionOption options for creating a branch protection
type CreateBranchProtectionOption struct {
BranchName string `json:"branch_name"`
EnablePush bool `json:"enable_push"`
EnablePushWhitelist bool `json:"enable_push_whitelist"`
PushWhitelistUsernames []string `json:"push_whitelist_usernames"`
PushWhitelistTeams []string `json:"push_whitelist_teams"`
PushWhitelistDeployKeys bool `json:"push_whitelist_deploy_keys"`
EnableMergeWhitelist bool `json:"enable_merge_whitelist"`
MergeWhitelistUsernames []string `json:"merge_whitelist_usernames"`
MergeWhitelistTeams []string `json:"merge_whitelist_teams"`
EnableStatusCheck bool `json:"enable_status_check"`
StatusCheckContexts []string `json:"status_check_contexts"`
RequiredApprovals int64 `json:"required_approvals"`
EnableApprovalsWhitelist bool `json:"enable_approvals_whitelist"`
ApprovalsWhitelistUsernames []string `json:"approvals_whitelist_username"`
ApprovalsWhitelistTeams []string `json:"approvals_whitelist_teams"`
BlockOnRejectedReviews bool `json:"block_on_rejected_reviews"`
BlockOnOutdatedBranch bool `json:"block_on_outdated_branch"`
DismissStaleApprovals bool `json:"dismiss_stale_approvals"`
RequireSignedCommits bool `json:"require_signed_commits"`
ProtectedFilePatterns string `json:"protected_file_patterns"`
}
// EditBranchProtectionOption options for editing a branch protection
type EditBranchProtectionOption struct {
EnablePush *bool `json:"enable_push"`
EnablePushWhitelist *bool `json:"enable_push_whitelist"`
PushWhitelistUsernames []string `json:"push_whitelist_usernames"`
PushWhitelistTeams []string `json:"push_whitelist_teams"`
PushWhitelistDeployKeys *bool `json:"push_whitelist_deploy_keys"`
EnableMergeWhitelist *bool `json:"enable_merge_whitelist"`
MergeWhitelistUsernames []string `json:"merge_whitelist_usernames"`
MergeWhitelistTeams []string `json:"merge_whitelist_teams"`
EnableStatusCheck *bool `json:"enable_status_check"`
StatusCheckContexts []string `json:"status_check_contexts"`
RequiredApprovals *int64 `json:"required_approvals"`
EnableApprovalsWhitelist *bool `json:"enable_approvals_whitelist"`
ApprovalsWhitelistUsernames []string `json:"approvals_whitelist_username"`
ApprovalsWhitelistTeams []string `json:"approvals_whitelist_teams"`
BlockOnRejectedReviews *bool `json:"block_on_rejected_reviews"`
BlockOnOutdatedBranch *bool `json:"block_on_outdated_branch"`
DismissStaleApprovals *bool `json:"dismiss_stale_approvals"`
RequireSignedCommits *bool `json:"require_signed_commits"`
ProtectedFilePatterns *string `json:"protected_file_patterns"`
}
// ListBranchProtectionsOptions list branch protection options
type ListBranchProtectionsOptions struct {
ListOptions
}
// ListBranchProtections list branch protections for a repo
func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtectionsOptions) ([]*BranchProtection, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
bps := make([]*BranchProtection, 0, 5)
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo))
link.RawQuery = opt.getURLQuery().Encode()
return bps, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &bps)
}
// GetBranchProtection gets a branch protection
func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
bp := new(BranchProtection)
return bp, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil, bp)
}
// CreateBranchProtection creates a branch protection for a repo
func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProtectionOption) (*BranchProtection, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
bp := new(BranchProtection)
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
return bp, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo), jsonHeader, bytes.NewReader(body), bp)
}
// EditBranchProtection edits a branch protection for a repo
func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchProtectionOption) (*BranchProtection, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
bp := new(BranchProtection)
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
return bp, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), bp)
}
// DeleteBranchProtection deletes a branch protection for a repo
func (c *Client) DeleteBranchProtection(owner, repo, name string) error {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return err
}
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil)
return err
}

View File

@ -10,20 +10,23 @@ import (
"fmt"
)
// ListCollaboratorsOptions options for listing a repository's collaborators
type ListCollaboratorsOptions struct {
ListOptions
}
// ListCollaborators list a repository's collaborators
func (c *Client) ListCollaborators(user, repo string) ([]*User, error) {
collaborators := make([]*User, 0, 10)
err := c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/collaborators", user, repo),
func (c *Client) ListCollaborators(user, repo string, opt ListCollaboratorsOptions) ([]*User, error) {
opt.setDefaults()
collaborators := make([]*User, 0, opt.PageSize)
return collaborators, c.getParsedResponse("GET",
fmt.Sprintf("/repos/%s/%s/collaborators?%s", user, repo, opt.getURLQuery().Encode()),
nil, nil, &collaborators)
return collaborators, err
}
// IsCollaborator check if a user is a collaborator of a repository
func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) {
status, err := c.getStatusCode("GET",
fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator),
nil, nil)
status, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil)
if err != nil {
return false, err
}
@ -51,7 +54,6 @@ func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollabo
// DeleteCollaborator remove a collaborator from a repository
func (c *Client) DeleteCollaborator(user, repo, collaborator string) error {
_, 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
}

View File

@ -7,6 +7,8 @@ package gitea
import (
"fmt"
"net/url"
"time"
)
// Identity for a person's identity like an author or committer
@ -46,8 +48,39 @@ type Commit struct {
Parents []*CommitMeta `json:"parents"`
}
// CommitDateOptions store dates for GIT_AUTHOR_DATE and GIT_COMMITTER_DATE
type CommitDateOptions struct {
Author time.Time `json:"author"`
Committer time.Time `json:"committer"`
}
// GetSingleCommit returns a single commit
func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, error) {
commit := new(Commit)
return commit, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/commits/%s", user, repo, commitID), nil, nil, &commit)
}
// ListCommitOptions list commit options
type ListCommitOptions struct {
ListOptions
//SHA or branch to start listing commits from (usually 'master')
SHA string
}
// QueryEncode turns options into querystring argument
func (opt *ListCommitOptions) QueryEncode() string {
query := opt.ListOptions.getURLQuery()
if opt.SHA != "" {
query.Add("sha", opt.SHA)
}
return query.Encode()
}
// ListRepoCommits return list of commits from a repo
func (c *Client) ListRepoCommits(user, repo string, opt ListCommitOptions) ([]*Commit, error) {
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/commits", user, repo))
opt.setDefaults()
commits := make([]*Commit, 0, opt.PageSize)
link.RawQuery = opt.QueryEncode()
return commits, c.getParsedResponse("GET", link.String(), nil, nil, &commits)
}

View File

@ -6,11 +6,158 @@
package gitea
import (
"bytes"
"encoding/json"
"fmt"
)
// FileOptions options for all file APIs
type FileOptions struct {
// message (optional) for the commit of this file. if not supplied, a default message will be used
Message string `json:"message"`
// branch (optional) to base this file from. if not given, the default branch is used
BranchName string `json:"branch"`
// new_branch (optional) will make a new branch from `branch` before creating the file
NewBranchName string `json:"new_branch"`
// `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
Author Identity `json:"author"`
Committer Identity `json:"committer"`
Dates CommitDateOptions `json:"dates"`
}
// CreateFileOptions options for creating files
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
type CreateFileOptions struct {
FileOptions
// content must be base64 encoded
// required: true
Content string `json:"content"`
}
// DeleteFileOptions options for deleting files (used for other File structs below)
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
type DeleteFileOptions struct {
FileOptions
// sha is the SHA for the file that already exists
// required: true
SHA string `json:"sha"`
}
// UpdateFileOptions options for updating files
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
type UpdateFileOptions struct {
FileOptions
// sha is the SHA for the file that already exists
// required: true
SHA string `json:"sha"`
// content must be base64 encoded
// required: true
Content string `json:"content"`
// from_path (optional) is the path of the original file which will be moved/renamed to the path in the URL
FromPath string `json:"from_path"`
}
// FileLinksResponse contains the links for a repo's file
type FileLinksResponse struct {
Self *string `json:"self"`
GitURL *string `json:"git"`
HTMLURL *string `json:"html"`
}
// ContentsResponse contains information about a repo's entry's (dir, file, symlink, submodule) metadata and content
type ContentsResponse struct {
Name string `json:"name"`
Path string `json:"path"`
SHA string `json:"sha"`
// `type` will be `file`, `dir`, `symlink`, or `submodule`
Type string `json:"type"`
Size int64 `json:"size"`
// `encoding` is populated when `type` is `file`, otherwise null
Encoding *string `json:"encoding"`
// `content` is populated when `type` is `file`, otherwise null
Content *string `json:"content"`
// `target` is populated when `type` is `symlink`, otherwise null
Target *string `json:"target"`
URL *string `json:"url"`
HTMLURL *string `json:"html_url"`
GitURL *string `json:"git_url"`
DownloadURL *string `json:"download_url"`
// `submodule_git_url` is populated when `type` is `submodule`, otherwise null
SubmoduleGitURL *string `json:"submodule_git_url"`
Links *FileLinksResponse `json:"_links"`
}
// FileCommitResponse contains information generated from a Git commit for a repo's file.
type FileCommitResponse struct {
CommitMeta
HTMLURL string `json:"html_url"`
Author *CommitUser `json:"author"`
Committer *CommitUser `json:"committer"`
Parents []*CommitMeta `json:"parents"`
Message string `json:"message"`
Tree *CommitMeta `json:"tree"`
}
// FileResponse contains information about a repo's file
type FileResponse struct {
Content *ContentsResponse `json:"content"`
Commit *FileCommitResponse `json:"commit"`
Verification *PayloadCommitVerification `json:"verification"`
}
// FileDeleteResponse contains information about a repo's file that was deleted
type FileDeleteResponse struct {
Content interface{} `json:"content"` // to be set to nil
Commit *FileCommitResponse `json:"commit"`
Verification *PayloadCommitVerification `json:"verification"`
}
// GetFile downloads a file of repository, ref can be branch/tag/commit.
// e.g.: ref -> master, tree -> macaron.go(no leading slash)
func (c *Client) GetFile(user, repo, ref, tree string) ([]byte, error) {
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
// ref is optional
func (c *Client) GetContents(owner, repo, ref, filepath string) (*ContentsResponse, error) {
cr := new(ContentsResponse)
return cr, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", owner, repo, filepath, ref), jsonHeader, nil, cr)
}
// CreateFile create a file in a repository
func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
fr := new(FileResponse)
return fr, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr)
}
// UpdateFile update a file in a repository
func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
fr := new(FileResponse)
return fr, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr)
}
// DeleteFile delete a file from repository
func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) error {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body))
if err != nil {
return err
}
if status != 200 && status != 204 {
return fmt.Errorf("unexpected Status: %d", status)
}
return nil
}

View File

@ -8,6 +8,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"time"
)
@ -24,10 +25,32 @@ type DeployKey struct {
Repository *Repository `json:"repository,omitempty"`
}
// ListDeployKeysOptions options for listing a repository's deploy keys
type ListDeployKeysOptions struct {
ListOptions
KeyID int64
Fingerprint string
}
// QueryEncode turns options into querystring argument
func (opt *ListDeployKeysOptions) QueryEncode() string {
query := opt.getURLQuery()
if opt.KeyID > 0 {
query.Add("key_id", fmt.Sprintf("%d", opt.KeyID))
}
if len(opt.Fingerprint) > 0 {
query.Add("fingerprint", opt.Fingerprint)
}
return query.Encode()
}
// ListDeployKeys list all the deploy keys of one repository
func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) {
keys := make([]*DeployKey, 0, 10)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys)
func (c *Client) ListDeployKeys(user, repo string, opt ListDeployKeysOptions) ([]*DeployKey, error) {
link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/keys", user, repo))
opt.setDefaults()
link.RawQuery = opt.QueryEncode()
keys := make([]*DeployKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", link.String(), nil, nil, &keys)
}
// GetDeployKey get one deploy key with key id

View File

@ -17,8 +17,14 @@ type Tag struct {
TarballURL string `json:"tarball_url"`
}
// ListRepoTags list all the branches of one repository
func (c *Client) ListRepoTags(user, repo string) ([]*Tag, error) {
tags := make([]*Tag, 0, 10)
return tags, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags", user, repo), nil, nil, &tags)
// ListRepoTagsOptions options for listing a repository's tags
type ListRepoTagsOptions struct {
ListOptions
}
// ListRepoTags list all the branches of one repository
func (c *Client) ListRepoTags(user, repo string, opt ListRepoTagsOptions) ([]*Tag, error) {
opt.setDefaults()
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)
}

View File

@ -10,24 +10,37 @@ import (
"fmt"
)
// TopicsList represents a list of repo's topics
type TopicsList struct {
// ListRepoTopicsOptions options for listing repo's topics
type ListRepoTopicsOptions struct {
ListOptions
}
// topicsList represents a list of repo's topics
type topicsList struct {
Topics []string `json:"topics"`
}
// ListRepoTopics list all repository's topics
func (c *Client) ListRepoTopics(user, repo string) (*TopicsList, error) {
var list TopicsList
return &list, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics", user, repo), nil, nil, &list)
func (c *Client) ListRepoTopics(user, repo string, opt ListRepoTopicsOptions) ([]string, error) {
opt.setDefaults()
list := new(topicsList)
err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, list)
if err != nil {
return nil, err
}
return list.Topics, nil
}
// SetRepoTopics replaces the list of repo's topics
func (c *Client) SetRepoTopics(user, repo string, list TopicsList) error {
body, err := json.Marshal(&list)
func (c *Client) SetRepoTopics(user, repo string, list []string) error {
l := topicsList{Topics: list}
body, err := json.Marshal(&l)
if err != nil {
return err
}
_, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics", user, repo), jsonHeader, bytes.NewReader(body))
return err
}

32
vendor/code.gitea.io/sdk/gitea/repo_transfer.go generated vendored Normal file
View File

@ -0,0 +1,32 @@
// 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"
)
// TransferRepoOption options when transfer a repository's ownership
type TransferRepoOption struct {
// required: true
NewOwner string `json:"new_owner"`
// ID of the team or teams to add to the repository. Teams can only be added to organization-owned repositories.
TeamIDs *[]int64 `json:"team_ids"`
}
// TransferRepo transfers the ownership of a repository
func (c *Client) TransferRepo(owner, reponame string, opt TransferRepoOption) (*Repository, error) {
if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil {
return nil, err
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/transfer", owner, reponame), jsonHeader, bytes.NewReader(body), repo)
}

View File

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

View File

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

View File

@ -50,29 +50,25 @@ type CreateStatusOption struct {
}
// CreateStatus creates a new Status for a given Commit
//
// POST /repos/:owner/:repo/statuses/:sha
func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) {
body, err := json.Marshal(&opts)
if err != nil {
return nil, err
}
status := &Status{}
return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha),
jsonHeader, bytes.NewReader(body), status)
status := new(Status)
return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status)
}
// ListStatusesOption holds pagination information
// ListStatusesOption options for listing a repository's commit's statuses
type ListStatusesOption struct {
Page int
ListOptions
}
// ListStatuses returns all statuses for a given Commit
//
// GET /repos/:owner/:repo/commits/:ref/statuses
func (c *Client) ListStatuses(owner, repo, sha string, opts ListStatusesOption) ([]*Status, error) {
statuses := make([]*Status, 0, 10)
return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?page=%d", owner, repo, sha, opts.Page), nil, nil, &statuses)
func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, error) {
opt.setDefaults()
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)
}
// CombinedStatus holds the combined state of several statuses for a single commit
@ -87,9 +83,7 @@ type CombinedStatus struct {
}
// GetCombinedStatus returns the CombinedStatus for a given Commit
//
// GET /repos/:owner/:repo/commits/:ref/status
func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) {
status := &CombinedStatus{}
status := new(CombinedStatus)
return status, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, sha), nil, nil, status)
}

View File

@ -7,17 +7,10 @@ package gitea
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
)
// BasicAuthEncode generate base64 of basic auth head
func BasicAuthEncode(user, pass string) string {
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
}
// AccessToken represents an API access token.
type AccessToken struct {
ID int64 `json:"id"`
@ -26,11 +19,19 @@ type AccessToken struct {
TokenLastEight string `json:"token_last_eight"`
}
// ListAccessTokens lista all the access tokens of user
func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) {
tokens := make([]*AccessToken, 0, 10)
return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user),
http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens)
// ListAccessTokensOptions options for listing a users's access tokens
type ListAccessTokensOptions struct {
ListOptions
}
// ListAccessTokens lists all the access tokens of user
func (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) {
if len(c.username) == 0 {
return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed")
}
opts.setDefaults()
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)
}
// CreateAccessTokenOption options when create access token
@ -39,22 +40,23 @@ type CreateAccessTokenOption struct {
}
// CreateAccessToken create one access token with options
func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) {
func (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, error) {
if len(c.username) == 0 {
return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed")
}
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
t := new(AccessToken)
return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user),
http.Header{
"content-type": []string{"application/json"},
"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}},
bytes.NewReader(body), t)
return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", c.username), jsonHeader, bytes.NewReader(body), t)
}
// DeleteAccessToken delete token with key id
func (c *Client) DeleteAccessToken(user string, keyID int64) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/users/%s/tokens/%d", user, keyID),
http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, c.password)}}, nil)
func (c *Client) DeleteAccessToken(keyID int64) error {
if len(c.username) == 0 {
return 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
}

View File

@ -7,6 +7,7 @@ package gitea
import (
"bytes"
"encoding/json"
"fmt"
)
// Email an email address belonging to a user
@ -16,10 +17,16 @@ type Email struct {
Primary bool `json:"primary"`
}
// ListEmailsOptions options for listing current's user emails
type ListEmailsOptions struct {
ListOptions
}
// ListEmails all the email addresses of user
func (c *Client) ListEmails() ([]*Email, error) {
emails := make([]*Email, 0, 3)
return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails)
func (c *Client) ListEmails(opt ListEmailsOptions) ([]*Email, error) {
opt.setDefaults()
emails := make([]*Email, 0, opt.PageSize)
return emails, c.getParsedResponse("GET", fmt.Sprintf("/user/emails?%s", opt.getURLQuery().Encode()), nil, nil, &emails)
}
// CreateEmailOption options when creating email addresses

View File

@ -6,28 +6,42 @@ package gitea
import "fmt"
// ListFollowersOptions options for listing followers
type ListFollowersOptions struct {
ListOptions
}
// ListMyFollowers list all the followers of current user
func (c *Client) ListMyFollowers(page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users)
func (c *Client) ListMyFollowers(opt ListFollowersOptions) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?%s", opt.getURLQuery().Encode()), nil, nil, &users)
}
// ListFollowers list all the followers of one user
func (c *Client) ListFollowers(user string, page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users)
func (c *Client) ListFollowers(user string, opt ListFollowersOptions) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?%s", user, opt.getURLQuery().Encode()), nil, nil, &users)
}
// ListFollowingOptions options for listing a user's users being followed
type ListFollowingOptions struct {
ListOptions
}
// ListMyFollowing list all the users current user followed
func (c *Client) ListMyFollowing(page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users)
func (c *Client) ListMyFollowing(opt ListFollowingOptions) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?%s", opt.getURLQuery().Encode()), nil, nil, &users)
}
// ListFollowing list all the users the user followed
func (c *Client) ListFollowing(user string, page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users)
func (c *Client) ListFollowing(user string, opt ListFollowingOptions) ([]*User, error) {
opt.setDefaults()
users := make([]*User, 0, opt.PageSize)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?%s", user, opt.getURLQuery().Encode()), nil, nil, &users)
}
// IsFollowing if current user followed the target

View File

@ -33,16 +33,23 @@ type GPGKeyEmail struct {
Verified bool `json:"verified"`
}
// ListGPGKeysOptions options for listing a user's GPGKeys
type ListGPGKeysOptions struct {
ListOptions
}
// ListGPGKeys list all the GPG keys of the user
func (c *Client) ListGPGKeys(user string) ([]*GPGKey, error) {
keys := make([]*GPGKey, 0, 10)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys", user), nil, nil, &keys)
func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, error) {
opt.setDefaults()
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)
}
// ListMyGPGKeys list all the GPG keys of current user
func (c *Client) ListMyGPGKeys() ([]*GPGKey, error) {
keys := make([]*GPGKey, 0, 10)
return keys, c.getParsedResponse("GET", "/user/gpg_keys", nil, nil, &keys)
func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, error) {
opt.setDefaults()
keys := make([]*GPGKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys)
}
// GetGPGKey get current user's GPG key by key id

View File

@ -24,16 +24,23 @@ type PublicKey struct {
KeyType string `json:"key_type,omitempty"`
}
// ListPublicKeysOptions options for listing a user's PublicKeys
type ListPublicKeysOptions struct {
ListOptions
}
// ListPublicKeys list all the public keys of the user
func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 10)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys)
func (c *Client) ListPublicKeys(user string, opt ListPublicKeysOptions) ([]*PublicKey, error) {
opt.setDefaults()
keys := make([]*PublicKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys)
}
// ListMyPublicKeys list all the public keys of current user
func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 10)
return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys)
func (c *Client) ListMyPublicKeys(opt ListPublicKeysOptions) ([]*PublicKey, error) {
opt.setDefaults()
keys := make([]*PublicKey, 0, opt.PageSize)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/user/keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys)
}
// GetPublicKey get current user's public key by key id

View File

@ -1,14 +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"
import (
"fmt"
"net/url"
)
type searchUsersResponse struct {
Users []*User `json:"data"`
}
// SearchUsersOption options for SearchUsers
type SearchUsersOption struct {
ListOptions
KeyWord string
}
// QueryEncode turns options into querystring argument
func (opt *SearchUsersOption) QueryEncode() string {
query := make(url.Values)
if opt.Page > 0 {
query.Add("page", fmt.Sprintf("%d", opt.Page))
}
if opt.PageSize > 0 {
query.Add("limit", fmt.Sprintf("%d", opt.PageSize))
}
if len(opt.KeyWord) > 0 {
query.Add("q", opt.KeyWord)
}
return query.Encode()
}
// SearchUsers finds users by query
func (c *Client) SearchUsers(query string, limit int) ([]*User, error) {
func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, error) {
link, _ := url.Parse("/users/search")
link.RawQuery = opt.QueryEncode()
resp := new(searchUsersResponse)
err := c.getParsedResponse("GET", fmt.Sprintf("/users/search?q=%s&limit=%d", query, limit), nil, nil, &resp)
err := c.getParsedResponse("GET", link.String(), nil, nil, &resp)
return resp.Users, err
}

2
vendor/modules.txt vendored
View File

@ -1,4 +1,4 @@
# code.gitea.io/sdk/gitea v0.11.3
# code.gitea.io/sdk/gitea v0.12.0
code.gitea.io/sdk/gitea
# gitea.com/jolheiser/gitea-vet v0.1.0
gitea.com/jolheiser/gitea-vet