From 55714001b0c2ef50895c71a9f1b150af1021da05 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 03:20:09 +0200 Subject: [PATCH 01/46] first draft --- go.mod | 1 + go.sum | 4 + modules/migrations/base/downloader.go | 2 +- modules/migrations/base/pullrequest.go | 1 - modules/migrations/base/release.go | 1 + modules/migrations/base/review.go | 1 + modules/migrations/git.go | 2 +- modules/migrations/gitea.go | 23 +- modules/migrations/gitea_downloader.go | 573 ++++++++++++++++++ modules/migrations/github.go | 2 +- modules/migrations/gitlab.go | 2 +- modules/structs/repo.go | 1 + vendor/code.gitea.io/sdk/gitea/LICENSE | 20 + vendor/code.gitea.io/sdk/gitea/admin_org.go | 35 ++ vendor/code.gitea.io/sdk/gitea/admin_repo.go | 22 + vendor/code.gitea.io/sdk/gitea/admin_user.go | 97 +++ vendor/code.gitea.io/sdk/gitea/attachment.go | 95 +++ vendor/code.gitea.io/sdk/gitea/client.go | 153 +++++ vendor/code.gitea.io/sdk/gitea/doc.go | 5 + vendor/code.gitea.io/sdk/gitea/fork.go | 41 ++ vendor/code.gitea.io/sdk/gitea/git_blob.go | 24 + vendor/code.gitea.io/sdk/gitea/git_hook.go | 57 ++ vendor/code.gitea.io/sdk/gitea/go.mod | 8 + vendor/code.gitea.io/sdk/gitea/go.sum | 13 + vendor/code.gitea.io/sdk/gitea/hook.go | 125 ++++ vendor/code.gitea.io/sdk/gitea/issue.go | 207 +++++++ .../code.gitea.io/sdk/gitea/issue_comment.go | 109 ++++ vendor/code.gitea.io/sdk/gitea/issue_label.go | 133 ++++ .../sdk/gitea/issue_milestone.go | 110 ++++ .../code.gitea.io/sdk/gitea/issue_reaction.go | 98 +++ .../sdk/gitea/issue_stopwatch.go | 42 ++ .../sdk/gitea/issue_subscription.go | 82 +++ .../sdk/gitea/issue_tracked_time.go | 89 +++ .../code.gitea.io/sdk/gitea/list_options.go | 37 ++ .../code.gitea.io/sdk/gitea/notifications.go | 137 +++++ vendor/code.gitea.io/sdk/gitea/oauth2.go | 87 +++ vendor/code.gitea.io/sdk/gitea/org.go | 98 +++ vendor/code.gitea.io/sdk/gitea/org_member.go | 98 +++ vendor/code.gitea.io/sdk/gitea/org_team.go | 148 +++++ vendor/code.gitea.io/sdk/gitea/org_type.go | 27 + vendor/code.gitea.io/sdk/gitea/pull.go | 196 ++++++ vendor/code.gitea.io/sdk/gitea/pull_review.go | 184 ++++++ vendor/code.gitea.io/sdk/gitea/release.go | 108 ++++ vendor/code.gitea.io/sdk/gitea/repo.go | 290 +++++++++ vendor/code.gitea.io/sdk/gitea/repo_branch.go | 91 +++ .../sdk/gitea/repo_branch_protection.go | 148 +++++ .../sdk/gitea/repo_collaborator.go | 59 ++ vendor/code.gitea.io/sdk/gitea/repo_commit.go | 86 +++ vendor/code.gitea.io/sdk/gitea/repo_file.go | 192 ++++++ vendor/code.gitea.io/sdk/gitea/repo_key.go | 76 +++ vendor/code.gitea.io/sdk/gitea/repo_refs.go | 69 +++ vendor/code.gitea.io/sdk/gitea/repo_tag.go | 30 + vendor/code.gitea.io/sdk/gitea/repo_topics.go | 58 ++ .../code.gitea.io/sdk/gitea/repo_transfer.go | 32 + vendor/code.gitea.io/sdk/gitea/repo_tree.go | 40 ++ vendor/code.gitea.io/sdk/gitea/repo_watch.go | 73 +++ vendor/code.gitea.io/sdk/gitea/status.go | 89 +++ vendor/code.gitea.io/sdk/gitea/user.go | 43 ++ vendor/code.gitea.io/sdk/gitea/user_app.go | 62 ++ vendor/code.gitea.io/sdk/gitea/user_email.go | 62 ++ vendor/code.gitea.io/sdk/gitea/user_follow.go | 69 +++ vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 82 +++ vendor/code.gitea.io/sdk/gitea/user_key.go | 76 +++ vendor/code.gitea.io/sdk/gitea/user_search.go | 44 ++ vendor/code.gitea.io/sdk/gitea/version.go | 57 ++ .../hashicorp/go-version/.travis.yml | 13 + .../github.com/hashicorp/go-version/LICENSE | 354 +++++++++++ .../github.com/hashicorp/go-version/README.md | 65 ++ .../hashicorp/go-version/constraint.go | 204 +++++++ vendor/github.com/hashicorp/go-version/go.mod | 1 + .../hashicorp/go-version/version.go | 380 ++++++++++++ .../go-version/version_collection.go | 17 + vendor/modules.txt | 5 + 73 files changed, 6155 insertions(+), 10 deletions(-) create mode 100644 modules/migrations/gitea_downloader.go create mode 100644 vendor/code.gitea.io/sdk/gitea/LICENSE create mode 100644 vendor/code.gitea.io/sdk/gitea/admin_org.go create mode 100644 vendor/code.gitea.io/sdk/gitea/admin_repo.go create mode 100644 vendor/code.gitea.io/sdk/gitea/admin_user.go create mode 100644 vendor/code.gitea.io/sdk/gitea/attachment.go create mode 100644 vendor/code.gitea.io/sdk/gitea/client.go create mode 100644 vendor/code.gitea.io/sdk/gitea/doc.go create mode 100644 vendor/code.gitea.io/sdk/gitea/fork.go create mode 100644 vendor/code.gitea.io/sdk/gitea/git_blob.go create mode 100644 vendor/code.gitea.io/sdk/gitea/git_hook.go create mode 100644 vendor/code.gitea.io/sdk/gitea/go.mod create mode 100644 vendor/code.gitea.io/sdk/gitea/go.sum create mode 100644 vendor/code.gitea.io/sdk/gitea/hook.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_comment.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_label.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_milestone.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_reaction.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_subscription.go create mode 100644 vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go create mode 100644 vendor/code.gitea.io/sdk/gitea/list_options.go create mode 100644 vendor/code.gitea.io/sdk/gitea/notifications.go create mode 100644 vendor/code.gitea.io/sdk/gitea/oauth2.go create mode 100644 vendor/code.gitea.io/sdk/gitea/org.go create mode 100644 vendor/code.gitea.io/sdk/gitea/org_member.go create mode 100644 vendor/code.gitea.io/sdk/gitea/org_team.go create mode 100644 vendor/code.gitea.io/sdk/gitea/org_type.go create mode 100644 vendor/code.gitea.io/sdk/gitea/pull.go create mode 100644 vendor/code.gitea.io/sdk/gitea/pull_review.go create mode 100644 vendor/code.gitea.io/sdk/gitea/release.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_branch.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_collaborator.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_commit.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_file.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_key.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_refs.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_tag.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_topics.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_transfer.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_tree.go create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_watch.go create mode 100644 vendor/code.gitea.io/sdk/gitea/status.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_app.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_email.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_follow.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_gpgkey.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_key.go create mode 100644 vendor/code.gitea.io/sdk/gitea/user_search.go create mode 100644 vendor/code.gitea.io/sdk/gitea/version.go create mode 100644 vendor/github.com/hashicorp/go-version/.travis.yml create mode 100644 vendor/github.com/hashicorp/go-version/LICENSE create mode 100644 vendor/github.com/hashicorp/go-version/README.md create mode 100644 vendor/github.com/hashicorp/go-version/constraint.go create mode 100644 vendor/github.com/hashicorp/go-version/go.mod create mode 100644 vendor/github.com/hashicorp/go-version/version.go create mode 100644 vendor/github.com/hashicorp/go-version/version_collection.go diff --git a/go.mod b/go.mod index 499e215fd11b..fd389e8bb5b9 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.14 require ( cloud.google.com/go v0.45.0 // indirect code.gitea.io/gitea-vet v0.2.1 + code.gitea.io/sdk/gitea v0.12.1 gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 diff --git a/go.sum b/go.sum index 3ea4c6e220d4..4d7cff88eb8a 100644 --- a/go.sum +++ b/go.sum @@ -11,6 +11,8 @@ cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbf cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= +code.gitea.io/sdk/gitea v0.12.1 h1:bMgjEqPnNX/i6TpVwXwpjJtFOnUSuC9P6yy/jjy8sjY= +code.gitea.io/sdk/gitea v0.12.1/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b h1:vXt85uYV17KURaUlhU7v4GbCShkqRZDSfo0TkC0YCjQ= @@ -400,6 +402,8 @@ github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrj github.com/hashicorp/go-retryablehttp v0.6.4/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP3V9oNE4hmsM= github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= +github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= diff --git a/modules/migrations/base/downloader.go b/modules/migrations/base/downloader.go index b692969ba501..ae12e6083c86 100644 --- a/modules/migrations/base/downloader.go +++ b/modules/migrations/base/downloader.go @@ -15,7 +15,7 @@ import ( // AssetDownloader downloads an asset (attachment) for a release type AssetDownloader interface { - GetAsset(tag string, id int64) (io.ReadCloser, error) + GetAsset(relTag string, relID, id int64) (io.ReadCloser, error) } // Downloader downloads the site repo informations diff --git a/modules/migrations/base/pullrequest.go b/modules/migrations/base/pullrequest.go index 964512e1377e..ee612fbb8e83 100644 --- a/modules/migrations/base/pullrequest.go +++ b/modules/migrations/base/pullrequest.go @@ -31,7 +31,6 @@ type PullRequest struct { MergeCommitSHA string Head PullRequestBranch Base PullRequestBranch - Assignee string Assignees []string IsLocked bool Reactions []*Reaction diff --git a/modules/migrations/base/release.go b/modules/migrations/base/release.go index 2a223920c77c..c9b26ab1dae0 100644 --- a/modules/migrations/base/release.go +++ b/modules/migrations/base/release.go @@ -15,6 +15,7 @@ type ReleaseAsset struct { DownloadCount *int Created time.Time Updated time.Time + DownloadURL *string } // Release represents a release diff --git a/modules/migrations/base/review.go b/modules/migrations/base/review.go index 8051fed653b3..0a9d03dae902 100644 --- a/modules/migrations/base/review.go +++ b/modules/migrations/base/review.go @@ -36,6 +36,7 @@ type ReviewComment struct { TreePath string DiffHunk string Position int + Line int CommitID string PosterID int64 Reactions []*Reaction diff --git a/modules/migrations/git.go b/modules/migrations/git.go index 5c9acb2533f2..7128ee60c2af 100644 --- a/modules/migrations/git.go +++ b/modules/migrations/git.go @@ -66,7 +66,7 @@ func (g *PlainGitDownloader) GetReleases() ([]*base.Release, error) { } // GetAsset returns an asset -func (g *PlainGitDownloader) GetAsset(_ string, _ int64) (io.ReadCloser, error) { +func (g *PlainGitDownloader) GetAsset(_ string, _, _ int64) (io.ReadCloser, error) { return nil, ErrNotSupported } diff --git a/modules/migrations/gitea.go b/modules/migrations/gitea.go index 082ddcd5fb0e..2054f9ad7731 100644 --- a/modules/migrations/gitea.go +++ b/modules/migrations/gitea.go @@ -272,9 +272,18 @@ func (g *GiteaLocalUploader) CreateReleases(downloader base.Downloader, releases // download attachment err = func() error { - rc, err := downloader.GetAsset(rel.TagName, asset.ID) - if err != nil { - return err + var rc io.ReadCloser + if asset.DownloadURL == nil { + rc, err = downloader.GetAsset(rel.TagName, rel.ID, asset.ID) + if err != nil { + return err + } + } else { + resp, err := http.Get(*asset.DownloadURL) + if err != nil { + return err + } + rc = resp.Body } _, err = storage.Attachments.Save(attach.RelativePath(), rc) return err @@ -778,8 +787,12 @@ func (g *GiteaLocalUploader) CreateReviews(reviews ...*base.Review) error { } for _, comment := range review.Comments { - _, _, line, _ := git.ParseDiffHunkString(comment.DiffHunk) - + line := comment.Line + if line != 0 { + comment.Position = 1 + } else { + _, _, line, _ = git.ParseDiffHunkString(comment.DiffHunk) + } headCommitID, err := g.gitRepo.GetRefCommitID(pr.GetGitRefName()) if err != nil { return fmt.Errorf("GetRefCommitID[%s]: %v", pr.GetGitRefName(), err) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go new file mode 100644 index 000000000000..7a058c38bb09 --- /dev/null +++ b/modules/migrations/gitea_downloader.go @@ -0,0 +1,573 @@ +// 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 migrations + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/migrations/base" + "code.gitea.io/gitea/modules/structs" + + "code.gitea.io/sdk/gitea" +) + +var ( + _ base.Downloader = &GiteaDownloader{} + _ base.DownloaderFactory = &GiteaDownloaderFactory{} +) + +func init() { + RegisterDownloaderFactory(&GiteaDownloaderFactory{}) +} + +// GiteaDownloaderFactory defines a gitea downloader factory +type GiteaDownloaderFactory struct { +} + +// New returns a Downloader related to this factory according MigrateOptions +func (f *GiteaDownloaderFactory) New(opts base.MigrateOptions) (base.Downloader, error) { + u, err := url.Parse(opts.CloneAddr) + if err != nil { + return nil, err + } + + baseURL := u.Scheme + "://" + u.Host + repoNameSpace := strings.TrimPrefix(u.Path, "/") + repoNameSpace = strings.TrimSuffix(repoNameSpace, ".git") + + path := strings.Split(repoNameSpace, "/") + if len(path) < 2 { + return nil, fmt.Errorf("invalid path") + } + + //ToDo handle gitea installed in subpath ... + repoPath := repoNameSpace + + log.Trace("Create gitea downloader. BaseURL: %s RepoName: %s", baseURL, repoNameSpace) + + return NewGiteaDownloader(baseURL, repoPath, opts.AuthUsername, opts.AuthPassword, opts.AuthToken), nil +} + +// GitServiceType returns the type of git service +func (f *GiteaDownloaderFactory) GitServiceType() structs.GitServiceType { + return structs.GiteaService +} + +// GiteaDownloader implements a Downloader interface to get repository information's +type GiteaDownloader struct { + ctx context.Context + client *gitea.Client + repoOwner string + repoName string +} + +// NewGiteaDownloader creates a gitea Downloader via gitea API +// Use either a username/password, personal token entered into the username field, or anonymous/public access +// Note: Public access only allows very basic access +func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *GiteaDownloader { + giteaClient := gitea.NewClient(baseURL, token) + if token == "" { + giteaClient.SetBasicAuth(username, password) + } + + path := strings.Split(repoPath, "/") + + return &GiteaDownloader{ + ctx: context.Background(), + client: giteaClient, + repoOwner: path[0], + repoName: path[1], + } +} + +// SetContext set context +func (g *GiteaDownloader) SetContext(ctx context.Context) { + g.ctx = ctx +} + +// GetRepoInfo returns a repository information +func (g *GiteaDownloader) GetRepoInfo() (*base.Repository, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + + repo, err := g.client.GetRepo(g.repoOwner, g.repoName) + if err != nil { + return nil, err + } + + return &base.Repository{ + Name: repo.Name, + Owner: repo.Owner.UserName, + IsPrivate: repo.Private, + Description: repo.Description, + CloneURL: repo.CloneURL, + OriginalURL: repo.HTMLURL, + }, nil +} + +// GetTopics return gitea topics +func (g *GiteaDownloader) GetTopics() ([]string, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + + return g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea.ListRepoTopicsOptions{}) +} + +// GetMilestones returns milestones +func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + var perPage = 50 + var milestones = make([]*base.Milestone, 0, perPage) + + for i := 1; ; i++ { + ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea.ListMilestoneOption{ + ListOptions: gitea.ListOptions{ + PageSize: perPage, + Page: i, + }, + State: gitea.StateAll, + }) + if err != nil { + return nil, err + } + + for i := range ms { + var state = "open" + + // ToDo: expose this info + createdAT := time.Now() + var updatedAT *time.Time + if ms[i].Closed != nil { + createdAT = *ms[i].Closed + updatedAT = ms[i].Closed + } + + milestones = append(milestones, &base.Milestone{ + Title: ms[i].Title, + Description: ms[i].Description, + Deadline: ms[i].Deadline, + Created: createdAT, + Updated: updatedAT, + Closed: ms[i].Closed, + State: state, + }) + } + if len(ms) < perPage { + break + } + } + return milestones, nil +} + +// GetLabels returns labels +func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + + var perPage = 50 + var labels = make([]*base.Label, 0, perPage) + + for i := 1; ; i++ { + ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{ + PageSize: perPage, + Page: i, + }}) + if err != nil { + return nil, err + } + + for i := range ls { + labels = append(labels, &base.Label{ + Name: ls[i].Name, + Color: ls[i].Color, + Description: ls[i].Description, + }) + } + if len(ls) < perPage { + break + } + } + return labels, nil +} + +func (g *GiteaDownloader) convertGiteaRelease(rel *gitea.Release) *base.Release { + r := &base.Release{ + TagName: rel.TagName, + Name: rel.Title, + Body: rel.Note, + Draft: rel.IsDraft, + Prerelease: rel.IsPrerelease, + PublisherID: rel.Publisher.ID, + PublisherName: rel.Publisher.UserName, + PublisherEmail: rel.Publisher.Email, + Published: rel.PublishedAt, + Created: rel.CreatedAt, + } + + for _, asset := range rel.Attachments { + size := int(asset.Size) + dlCount := int(asset.DownloadCount) + r.Assets = append(r.Assets, base.ReleaseAsset{ + ID: asset.ID, + Name: asset.Name, + Size: &size, + DownloadCount: &dlCount, + Created: asset.Created, + DownloadURL: &asset.DownloadURL, + }) + } + return r +} + +// GetReleases returns releases +func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { + var perPage = 100 + var releases = make([]*base.Release, 0, perPage) + for i := 1; ; i++ { + rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea.ListReleasesOptions{ListOptions: gitea.ListOptions{ + PageSize: perPage, + Page: i, + }}) + if err != nil { + return nil, err + } + + for i := range rl { + releases = append(releases, g.convertGiteaRelease(rl[i])) + } + if len(rl) < perPage { + break + } + } + return releases, nil +} + +// GetAsset returns an asset +func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, error) { + + asset, err := g.client.GetReleaseAttachment(g.repoOwner, g.repoName, relID, id) + if err != nil { + return nil, err + } + resp, err := http.Get(asset.DownloadURL) + if err != nil { + return nil, err + } + + // resp.Body is closed by the uploader + return resp.Body, nil +} + +// getIssueReactions +func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, error) { + var reactions []*base.Reaction + for i := 1; ; i++ { + rl, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) + if err != nil { + return nil, err + } + if len(rl) == 0 { + break + } + for _, reaction := range rl { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.ID, + UserName: reaction.User.UserName, + Content: reaction.Reaction, + }) + } + } + return reactions, nil +} + +// GetIssues returns issues according start and limit +func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { + + var allIssues = make([]*base.Issue, 0, perPage) + + issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea.ListIssueOption{ + ListOptions: gitea.ListOptions{Page: page, PageSize: perPage}, + State: gitea.StateAll, + Type: gitea.IssueTypeIssue, + }) + if err != nil { + return nil, false, fmt.Errorf("error while listing issues: %v", err) + } + for _, issue := range issues { + + var labels = make([]*base.Label, 0, len(issue.Labels)) + for i := range issue.Labels { + labels = append(labels, &base.Label{ + Name: issue.Labels[i].Name, + Color: issue.Labels[i].Color, + Description: issue.Labels[i].Description, + }) + } + + var milestone string + if issue.Milestone != nil { + milestone = issue.Milestone.Title + } + + reactions, err := g.getIssueReactions(issue.Index) + if err != nil { + return nil, false, fmt.Errorf("error while geting reactions: %v", err) + } + + allIssues = append(allIssues, &base.Issue{ + Title: issue.Title, + Number: issue.Index, + PosterID: issue.Poster.ID, + PosterName: issue.Poster.UserName, + PosterEmail: issue.Poster.Email, + Content: issue.Body, + Milestone: milestone, + State: string(issue.State), + Created: issue.Created, + Updated: issue.Updated, + Closed: issue.Closed, + Reactions: reactions, + Labels: labels, + // IsLocked: issue.IsLocked, // ToDo on sdk release v0.13.0 + }) + } + + return allIssues, len(issues) == 0, nil +} + +// GetComments returns comments according issueNumber +func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { + + var perPage = 50 + var allComments = make([]*base.Comment, 0, 100) + + for i := 1; ; i++ { + comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea.ListIssueCommentOptions{ListOptions: gitea.ListOptions{ + PageSize: perPage, + Page: i, + }}) + if err != nil { + return nil, fmt.Errorf("error while listing comments: %v", err) + } + if len(comments) == 0 { + break + } + for _, comment := range comments { + rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, comment.ID) + if err != nil { + return nil, err + } + var reactions []*base.Reaction + for i := range rl { + reactions = append(reactions, &base.Reaction{ + UserID: rl[i].User.ID, + UserName: rl[i].User.UserName, + Content: rl[i].Reaction, + }) + } + + allComments = append(allComments, &base.Comment{ + IssueIndex: index, + PosterID: comment.Poster.ID, + PosterName: comment.Poster.UserName, + PosterEmail: comment.Poster.Email, + Content: comment.Body, + Created: comment.Created, + Updated: comment.Updated, + Reactions: reactions, + }) + } + } + return allComments, nil +} + +// GetPullRequests returns pull requests according page and perPage +func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { + + var allPRs = make([]*base.PullRequest, 0, perPage) + + prs, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea.ListPullRequestsOptions{ + ListOptions: gitea.ListOptions{ + Page: page, + PageSize: perPage, + }, + State: gitea.StateAll, + }) + if err != nil { + return nil, fmt.Errorf("error while listing repos: %v", err) + } + for _, pr := range prs { + var milestone string + if pr.Milestone != nil { + milestone = pr.Milestone.Title + } + + var labels = make([]*base.Label, 0, len(pr.Labels)) + for i := range pr.Labels { + labels = append(labels, &base.Label{ + Name: pr.Labels[i].Name, + Color: pr.Labels[i].Color, + Description: pr.Labels[i].Description, + }) + } + + var ( + headUserName string + headRepoName string + headCloneURL string + headRef string + headSHA string + ) + if pr.Head != nil { + if pr.Head.Repository != nil { + headUserName = pr.Head.Repository.Owner.UserName + headRepoName = pr.Head.Repository.Name + } + headSHA = pr.Head.Sha + headRef = pr.Head.Ref + } + + var mergeCommitSHA string + if pr.MergedCommitID != nil { + mergeCommitSHA = *pr.MergedCommitID + } + + reactions, err := g.getIssueReactions(pr.Index) + if err != nil { + return nil, fmt.Errorf("error while geting reactions: %v", err) + } + + var assignees []string + for i := range pr.Assignees { + assignees = append(assignees, pr.Assignees[i].UserName) + } + + createdAt := time.Now() + if pr.Created != nil { + createdAt = *pr.Created + } + updatedAt := time.Now() + if pr.Created != nil { + updatedAt = *pr.Updated + } + + allPRs = append(allPRs, &base.PullRequest{ + Title: pr.Title, + Number: pr.Index, + PosterID: pr.Poster.ID, + PosterName: pr.Poster.UserName, + PosterEmail: pr.Poster.Email, + Content: pr.Body, + State: string(pr.State), + Created: createdAt, + Updated: updatedAt, + Closed: pr.Closed, + Labels: labels, + Milestone: milestone, + Reactions: reactions, + Assignees: assignees, + Merged: pr.HasMerged, + MergedTime: pr.Merged, + MergeCommitSHA: mergeCommitSHA, + // IsLocked: pr.IsLocked, sdk v0.13.0 TODO + PatchURL: pr.PatchURL, + Head: base.PullRequestBranch{ + Ref: headRef, + SHA: headSHA, + RepoName: headRepoName, + OwnerName: headUserName, + CloneURL: headCloneURL, + }, + Base: base.PullRequestBranch{ + Ref: pr.Base.Ref, + SHA: pr.Base.Sha, + RepoName: g.repoName, + OwnerName: g.repoOwner, + }, + }) + } + + return allPRs, nil +} + +// GetReviews returns pull requests review +func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { + + var perPage = 50 + var allReviews = make([]*base.Review, 0, perPage) + + for i := 1; ; i++ { + prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea.ListPullReviewsOptions{ListOptions: gitea.ListOptions{ + Page: i, + PageSize: perPage, + }}) + if err != nil { + return nil, err + } + + for _, pr := range prl { + + var reviewComments []*base.ReviewComment + for ii := 1; ; ii++ { + rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea.ListPullReviewsCommentsOptions{}) + if err != nil { + return nil, err + } + for i := range rcl { + line := int(rcl[i].LineNum) + if rcl[i].OldLineNum > 0 { + line = int(rcl[i].OldLineNum) * -1 + } + + reviewComments = append(reviewComments, &base.ReviewComment{ + ID: rcl[i].ID, + Content: rcl[i].Body, + TreePath: rcl[i].Path, + DiffHunk: rcl[i].DiffHunk, + Position: line, + CommitID: rcl[i].CommitID, + PosterID: rcl[i].Reviewer.ID, + CreatedAt: rcl[i].Created, + UpdatedAt: rcl[i].Updated, + }) + } + if len(rcl) < perPage { + break + } + } + + allReviews = append(allReviews, &base.Review{ + ID: pr.ID, + IssueIndex: index, + ReviewerID: pr.Reviewer.ID, + ReviewerName: pr.Reviewer.UserName, + Official: pr.Official, + CommitID: pr.CommitID, + Content: pr.Body, + CreatedAt: pr.Submitted, + State: string(pr.State), + Comments: reviewComments, + }) + } + + if len(prl) < perPage { + break + } + } + return allReviews, nil +} diff --git a/modules/migrations/github.go b/modules/migrations/github.go index eb73a7e0d403..e322171614ee 100644 --- a/modules/migrations/github.go +++ b/modules/migrations/github.go @@ -319,7 +319,7 @@ func (g *GithubDownloaderV3) GetReleases() ([]*base.Release, error) { } // GetAsset returns an asset -func (g *GithubDownloaderV3) GetAsset(_ string, id int64) (io.ReadCloser, error) { +func (g *GithubDownloaderV3) GetAsset(_ string, _, id int64) (io.ReadCloser, error) { asset, redir, err := g.client.Repositories.DownloadReleaseAsset(g.ctx, g.repoOwner, g.repoName, id, http.DefaultClient) if err != nil { return nil, err diff --git a/modules/migrations/gitlab.go b/modules/migrations/gitlab.go index eec16d24333a..7fc3fab0ec0e 100644 --- a/modules/migrations/gitlab.go +++ b/modules/migrations/gitlab.go @@ -304,7 +304,7 @@ func (g *GitlabDownloader) GetReleases() ([]*base.Release, error) { } // GetAsset returns an asset -func (g *GitlabDownloader) GetAsset(tag string, id int64) (io.ReadCloser, error) { +func (g *GitlabDownloader) GetAsset(tag string, _, id int64) (io.ReadCloser, error) { link, _, err := g.client.ReleaseLinks.GetReleaseLink(g.repoID, tag, int(id)) if err != nil { return nil, err diff --git a/modules/structs/repo.go b/modules/structs/repo.go index 808d2ffbc8ed..3a9a691ca4d4 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -250,6 +250,7 @@ var ( SupportedFullGitService = []GitServiceType{ GithubService, GitlabService, + GiteaService, } ) diff --git a/vendor/code.gitea.io/sdk/gitea/LICENSE b/vendor/code.gitea.io/sdk/gitea/LICENSE new file mode 100644 index 000000000000..10aeba46bcfc --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2016 The Gitea Authors +Copyright (c) 2014 The Gogs Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/code.gitea.io/sdk/gitea/admin_org.go b/vendor/code.gitea.io/sdk/gitea/admin_org.go new file mode 100644 index 000000000000..8b0bac18f35e --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_org.go @@ -0,0 +1,35 @@ +// Copyright 2015 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// AdminListOrgsOptions options for listing admin's organizations +type AdminListOrgsOptions struct { + ListOptions +} + +// AdminListOrgs lists all 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 +func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + org := new(Organization) + return org, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user), + jsonHeader, bytes.NewReader(body), org) +} diff --git a/vendor/code.gitea.io/sdk/gitea/admin_repo.go b/vendor/code.gitea.io/sdk/gitea/admin_repo.go new file mode 100644 index 000000000000..cf565ffa38b1 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_repo.go @@ -0,0 +1,22 @@ +// Copyright 2015 The Gogs 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" +) + +// AdminCreateRepo create a repo +func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + repo := new(Repository) + return repo, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user), + jsonHeader, bytes.NewReader(body), repo) +} diff --git a/vendor/code.gitea.io/sdk/gitea/admin_user.go b/vendor/code.gitea.io/sdk/gitea/admin_user.go new file mode 100644 index 000000000000..c447934395b0 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_user.go @@ -0,0 +1,97 @@ +// Copyright 2015 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// AdminListUsersOptions options for listing admin users +type AdminListUsersOptions struct { + ListOptions +} + +// AdminListUsers lists all 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 +type CreateUserOption struct { + SourceID int64 `json:"source_id"` + LoginName string `json:"login_name"` + Username string `json:"username"` + FullName string `json:"full_name"` + Email string `json:"email"` + Password string `json:"password"` + MustChangePassword *bool `json:"must_change_password"` + SendNotify bool `json:"send_notify"` +} + +// AdminCreateUser create a user +func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + user := new(User) + return user, c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user) +} + +// EditUserOption edit user options +type EditUserOption struct { + SourceID int64 `json:"source_id"` + LoginName string `json:"login_name"` + FullName string `json:"full_name"` + Email string `json:"email"` + Password string `json:"password"` + MustChangePassword *bool `json:"must_change_password"` + Website string `json:"website"` + Location string `json:"location"` + Active *bool `json:"active"` + Admin *bool `json:"admin"` + AllowGitHook *bool `json:"allow_git_hook"` + AllowImportLocal *bool `json:"allow_import_local"` + MaxRepoCreation *int `json:"max_repo_creation"` + ProhibitLogin *bool `json:"prohibit_login"` + AllowCreateOrganization *bool `json:"allow_create_organization"` +} + +// AdminEditUser modify user informations +func (c *Client) AdminEditUser(user string, opt EditUserOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body)) + return err +} + +// AdminDeleteUser delete one user according name +func (c *Client) AdminDeleteUser(user string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil) + return err +} + +// AdminCreateUserPublicKey adds a public key for the user +func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + key := new(PublicKey) + return key, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key) +} + +// AdminDeleteUserPublicKey deletes a user's public key +func (c *Client) AdminDeleteUserPublicKey(user string, keyID int) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s/keys/%d", user, keyID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/attachment.go b/vendor/code.gitea.io/sdk/gitea/attachment.go new file mode 100644 index 000000000000..a13787be86ab --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/attachment.go @@ -0,0 +1,95 @@ +// Copyright 2017 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 "code.gitea.io/sdk/gitea" +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "mime/multipart" + "net/http" + "time" +) + +// Attachment a generic attachment +type Attachment struct { + ID int64 `json:"id"` + Name string `json:"name"` + Size int64 `json:"size"` + DownloadCount int64 `json:"download_count"` + Created time.Time `json:"created_at"` + UUID string `json:"uuid"` + 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, opt ListReleaseAttachmentsOptions) ([]*Attachment, error) { + opt.setDefaults() + attachments := make([]*Attachment, 0, opt.PageSize) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/%d/assets?%s", user, repo, release, opt.getURLQuery().Encode()), + nil, nil, &attachments) + return attachments, err +} + +// GetReleaseAttachment returns the requested attachment +func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, error) { + a := new(Attachment) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), + nil, nil, &a) + return a, err +} + +// CreateReleaseAttachment creates an attachment for the given release +func (c *Client) CreateReleaseAttachment(user, repo string, release int64, file io.Reader, filename string) (*Attachment, error) { + // Write file to body + body := new(bytes.Buffer) + writer := multipart.NewWriter(body) + part, err := writer.CreateFormFile("attachment", filename) + if err != nil { + return nil, err + } + + if _, err = io.Copy(part, file); err != nil { + return nil, err + } + if err = writer.Close(); err != nil { + return nil, err + } + + // Send request + attachment := new(Attachment) + err = c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), + http.Header{"Content-Type": {writer.FormDataContentType()}}, body, &attachment) + return attachment, err +} + +// EditAttachmentOptions options for editing attachments +type EditAttachmentOptions struct { + Name string `json:"name"` +} + +// EditReleaseAttachment updates the given attachment with the given options +func (c *Client) EditReleaseAttachment(user, repo string, release int64, attachment int64, form EditAttachmentOptions) (*Attachment, error) { + body, err := json.Marshal(&form) + if err != nil { + return nil, err + } + attach := new(Attachment) + return attach, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, attachment), jsonHeader, bytes.NewReader(body), attach) +} + +// DeleteReleaseAttachment deletes the given attachment including the uploaded file +func (c *Client) DeleteReleaseAttachment(user, repo string, release int64, id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go new file mode 100644 index 000000000000..04f6a4cf2436 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -0,0 +1,153 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + "strings" + "sync" + + "github.com/hashicorp/go-version" +) + +var jsonHeader = http.Header{"content-type": []string{"application/json"}} + +// Version return the library version +func Version() string { + return "0.12.0" +} + +// Client represents a Gitea API client. +type Client struct { + url string + accessToken string + username string + password string + otp string + sudo string + client *http.Client + serverVersion *version.Version + versionLock sync.RWMutex +} + +// NewClient initializes and returns a API client. +func NewClient(url, token string) *Client { + return &Client{ + url: strings.TrimSuffix(url, "/"), + accessToken: token, + client: &http.Client{}, + } +} + +// NewClientWithHTTP creates an API client with a custom http client +func NewClientWithHTTP(url string, httpClient *http.Client) *Client { + client := NewClient(url, "") + client.client = httpClient + return client +} + +// SetBasicAuth sets basicauth +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 +} + +// SetSudo sets username to impersonate. +func (c *Client) SetSudo(sudo string) { + c.sudo = sudo +} + +func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) { + req, err := http.NewRequest(method, c.url+"/api/v1"+path, body) + if err != nil { + return nil, err + } + 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 len(c.sudo) != 0 { + req.Header.Set("Sudo", c.sudo) + } + for k, v := range header { + req.Header[k] = v + } + + return c.client.Do(req) +} + +func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) { + resp, err := c.doRequest(method, path, header, body) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + data, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + switch resp.StatusCode { + case 403: + return nil, errors.New("403 Forbidden") + case 404: + return nil, errors.New("404 Not Found") + case 409: + return nil, errors.New("409 Conflict") + case 422: + return nil, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) + } + + if resp.StatusCode/100 != 2 { + errMap := make(map[string]interface{}) + if err = json.Unmarshal(data, &errMap); err != nil { + // when the JSON can't be parsed, data was probably empty or a plain string, + // so we try to return a helpful error anyway + return nil, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data)) + } + return nil, errors.New(errMap["message"].(string)) + } + + return data, nil +} + +func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error { + data, err := c.getResponse(method, path, header, body) + if err != nil { + return err + } + return json.Unmarshal(data, obj) +} + +func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, error) { + resp, err := c.doRequest(method, path, header, body) + if err != nil { + return -1, err + } + defer resp.Body.Close() + + return resp.StatusCode, nil +} diff --git a/vendor/code.gitea.io/sdk/gitea/doc.go b/vendor/code.gitea.io/sdk/gitea/doc.go new file mode 100644 index 000000000000..6bd327db4623 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/doc.go @@ -0,0 +1,5 @@ +// Copyright 2016 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 "code.gitea.io/sdk/gitea" diff --git a/vendor/code.gitea.io/sdk/gitea/fork.go b/vendor/code.gitea.io/sdk/gitea/fork.go new file mode 100644 index 000000000000..fe197462c10c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/fork.go @@ -0,0 +1,41 @@ +// Copyright 2016 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" +) + +// ListForksOptions options for listing repository's forks +type ListForksOptions struct { + ListOptions +} + +// ListForks list a repository's forks +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) +} + +// CreateForkOption options for creating a fork +type CreateForkOption struct { + // organization name, if forking into an organization + Organization *string `json:"organization"` +} + +// CreateFork create a fork of a repository +func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Repository, error) { + body, err := json.Marshal(form) + if err != nil { + return nil, err + } + fork := new(Repository) + return fork, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork) +} diff --git a/vendor/code.gitea.io/sdk/gitea/git_blob.go b/vendor/code.gitea.io/sdk/gitea/git_blob.go new file mode 100644 index 000000000000..2843bc35833f --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/git_blob.go @@ -0,0 +1,24 @@ +// 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" +) + +// GitBlobResponse represents a git blob +type GitBlobResponse struct { + Content string `json:"content"` + Encoding string `json:"encoding"` + URL string `json:"url"` + SHA string `json:"sha"` + Size int64 `json:"size"` +} + +// GetBlob get the blob of a repository file +func (c *Client) GetBlob(user, repo, sha string) (*GitBlobResponse, error) { + blob := new(GitBlobResponse) + return blob, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/blobs/%s", user, repo, sha), nil, nil, blob) +} diff --git a/vendor/code.gitea.io/sdk/gitea/git_hook.go b/vendor/code.gitea.io/sdk/gitea/git_hook.go new file mode 100644 index 000000000000..1162d091167b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/git_hook.go @@ -0,0 +1,57 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// GitHook represents a Git repository hook +type GitHook struct { + Name string `json:"name"` + IsActive bool `json:"is_active"` + 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, 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 +func (c *Client) GetRepoGitHook(user, repo, id string) (*GitHook, error) { + h := new(GitHook) + return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil, h) +} + +// EditGitHookOption options when modifying one Git hook +type EditGitHookOption struct { + Content string `json:"content"` +} + +// EditRepoGitHook modify one Git hook of a repository +func (c *Client) EditRepoGitHook(user, repo, id string, opt EditGitHookOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), jsonHeader, bytes.NewReader(body)) + return err +} + +// DeleteRepoGitHook delete one Git hook from a repository +func (c *Client) DeleteRepoGitHook(user, repo, id string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/go.mod b/vendor/code.gitea.io/sdk/gitea/go.mod new file mode 100644 index 000000000000..7b0d75fd34b5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/go.mod @@ -0,0 +1,8 @@ +module code.gitea.io/sdk/gitea + +go 1.12 + +require ( + github.com/hashicorp/go-version v1.2.0 + github.com/stretchr/testify v1.4.0 +) diff --git a/vendor/code.gitea.io/sdk/gitea/go.sum b/vendor/code.gitea.io/sdk/gitea/go.sum new file mode 100644 index 000000000000..e210c1c42850 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/go.sum @@ -0,0 +1,13 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/code.gitea.io/sdk/gitea/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go new file mode 100644 index 000000000000..f89a6e952aa7 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/hook.go @@ -0,0 +1,125 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2017 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" +) + +// Hook a hook is a web hook when one repository changed +type Hook struct { + ID int64 `json:"id"` + Type string `json:"type"` + URL string `json:"-"` + Config map[string]string `json:"config"` + Events []string `json:"events"` + Active bool `json:"active"` + Updated time.Time `json:"updated_at"` + 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, 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, 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 +func (c *Client) GetOrgHook(org string, id int64) (*Hook, error) { + h := new(Hook) + return h, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil, h) +} + +// GetRepoHook get a hook of a repository +func (c *Client) GetRepoHook(user, repo string, id int64) (*Hook, error) { + h := new(Hook) + return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil, h) +} + +// CreateHookOption options when create a hook +type CreateHookOption struct { + Type string `json:"type"` + Config map[string]string `json:"config"` + Events []string `json:"events"` + BranchFilter string `json:"branch_filter"` + Active bool `json:"active"` +} + +// CreateOrgHook create one hook for an organization, with options +func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + h := new(Hook) + return h, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/hooks", org), jsonHeader, bytes.NewReader(body), h) +} + +// CreateRepoHook create one hook for a repository, with options +func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + h := new(Hook) + return h, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h) +} + +// EditHookOption options when modify one hook +type EditHookOption struct { + Config map[string]string `json:"config"` + Events []string `json:"events"` + BranchFilter string `json:"branch_filter"` + Active *bool `json:"active"` +} + +// EditOrgHook modify one hook of an organization, with hook id and options +func (c *Client) EditOrgHook(org string, id int64, opt EditHookOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), jsonHeader, bytes.NewReader(body)) + return err +} + +// EditRepoHook modify one hook of a repository, with hook id and options +func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body)) + return err +} + +// DeleteOrgHook delete one hook from an organization, with hook id +func (c *Client) DeleteOrgHook(org string, id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil) + return err +} + +// DeleteRepoHook delete one hook from a repository, with hook id +func (c *Client) DeleteRepoHook(user, repo string, id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue.go b/vendor/code.gitea.io/sdk/gitea/issue.go new file mode 100644 index 000000000000..0e57147f180e --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue.go @@ -0,0 +1,207 @@ +// Copyright 2016 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" + "net/url" + "strings" + "time" +) + +// PullRequestMeta PR info if an issue is a PR +type PullRequestMeta struct { + HasMerged bool `json:"merged"` + 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"` + URL string `json:"url"` + Index int64 `json:"number"` + Poster *User `json:"user"` + OriginalAuthor string `json:"original_author"` + OriginalAuthorID int64 `json:"original_author_id"` + Title string `json:"title"` + Body string `json:"body"` + Labels []*Label `json:"labels"` + Milestone *Milestone `json:"milestone"` + Assignee *User `json:"assignee"` + Assignees []*User `json:"assignees"` + // Whether the issue is open or closed + State StateType `json:"state"` + Comments int `json:"comments"` + Created time.Time `json:"created_at"` + Updated time.Time `json:"updated_at"` + 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 { + 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 + +const ( + // IssueTypeAll pr and issue + IssueTypeAll IssueType = "" + // IssueTypeIssue only issues + IssueTypeIssue IssueType = "issues" + // IssueTypePull only pulls + IssueTypePull IssueType = "pulls" +) + +// QueryEncode turns options into querystring argument +func (opt *ListIssueOption) QueryEncode() string { + query := opt.getURLQuery() + + if len(opt.State) > 0 { + query.Add("state", string(opt.State)) + } + + if len(opt.Labels) > 0 { + 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) { + opt.setDefaults() + issues := make([]*Issue, 0, opt.PageSize) + + 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, 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)) + 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, err +} + +// GetIssue returns a single issue for a given repository +func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { + issue := new(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 +type CreateIssueOption struct { + Title string `json:"title"` + Body string `json:"body"` + // username of assignee + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Deadline *time.Time `json:"due_date"` + // milestone id + Milestone int64 `json:"milestone"` + // list of label ids + Labels []int64 `json:"labels"` + Closed bool `json:"closed"` +} + +// CreateIssue create a new issue for a given repository +func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + issue := new(Issue) + return issue, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo), + jsonHeader, bytes.NewReader(body), issue) +} + +// EditIssueOption options for editing an issue +type EditIssueOption struct { + Title string `json:"title"` + Body *string `json:"body"` + Assignee *string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone *int64 `json:"milestone"` + State *StateType `json:"state"` + Deadline *time.Time `json:"due_date"` +} + +// EditIssue modify an existing issue for a given repository +func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + issue := new(Issue) + return issue, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), + jsonHeader, bytes.NewReader(body), issue) +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_comment.go b/vendor/code.gitea.io/sdk/gitea/issue_comment.go new file mode 100644 index 000000000000..cc8cf9fbdbab --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_comment.go @@ -0,0 +1,109 @@ +// Copyright 2016 The Gogs 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" +) + +// Comment represents a comment on a commit or issue +type Comment struct { + ID int64 `json:"id"` + HTMLURL string `json:"html_url"` + PRURL string `json:"pull_request_url"` + IssueURL string `json:"issue_url"` + Poster *User `json:"user"` + OriginalAuthor string `json:"original_author"` + OriginalAuthorID int64 `json:"original_author_id"` + Body string `json:"body"` + Created time.Time `json:"created_at"` + 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, 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, 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 +type CreateIssueCommentOption struct { + Body string `json:"body"` +} + +// CreateIssueComment create comment on an issue. +func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + comment := new(Comment) + return comment, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), jsonHeader, bytes.NewReader(body), comment) +} + +// EditIssueCommentOption options for editing a comment +type EditIssueCommentOption struct { + Body string `json:"body"` +} + +// EditIssueComment edits an issue comment. +func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + comment := new(Comment) + return comment, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), jsonHeader, bytes.NewReader(body), comment) +} + +// DeleteIssueComment deletes an issue comment. +func (c *Client) DeleteIssueComment(owner, repo string, commentID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_label.go b/vendor/code.gitea.io/sdk/gitea/issue_label.go new file mode 100644 index 000000000000..c5e560ab07d5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_label.go @@ -0,0 +1,133 @@ +// Copyright 2016 The Gogs 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" +) + +// Label a label to an issue or a pr +type Label struct { + ID int64 `json:"id"` + Name string `json:"name"` + // example: 00aabb + Color string `json:"color"` + Description string `json:"description"` + 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, 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 +// TODO: maybe we need get a label by name +func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, error) { + label := new(Label) + return label, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label) +} + +// CreateLabelOption options for creating a label +type CreateLabelOption struct { + Name string `json:"name"` + // example: #00aabb + Color string `json:"color"` + Description string `json:"description"` +} + +// CreateLabel create one label of repository +func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { + if len(opt.Color) == 6 { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + opt.Color = "#" + opt.Color + } + } + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + label := new(Label) + return label, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), + jsonHeader, bytes.NewReader(body), label) +} + +// EditLabelOption options for editing a label +type EditLabelOption struct { + Name *string `json:"name"` + Color *string `json:"color"` + Description *string `json:"description"` +} + +// EditLabel modify one label with options +func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + label := new(Label) + return label, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), label) +} + +// DeleteLabel delete one label of repository by id +// TODO: maybe we need delete by name +func (c *Client) DeleteLabel(owner, repo string, id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil) + return err +} + +// GetIssueLabels get labels of one issue via issue id +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?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels) +} + +// IssueLabelsOption a collection of labels +type IssueLabelsOption struct { + // list of label IDs + Labels []int64 `json:"labels"` +} + +// AddIssueLabels add one or more labels to one issue +func (c *Client) AddIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + var labels []*Label + return labels, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) +} + +// ReplaceIssueLabels replace old labels of issue with new labels +func (c *Client) ReplaceIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + var labels []*Label + return labels, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) +} + +// DeleteIssueLabel delete one label of one issue by issue id and label id +// TODO: maybe we need delete by label name and issue id +func (c *Client) DeleteIssueLabel(owner, repo string, index, label int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, index, label), nil, nil) + return err +} + +// ClearIssueLabels delete all the labels of one issue. +func (c *Client) ClearIssueLabels(owner, repo string, index int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go new file mode 100644 index 000000000000..41fca1fd5e75 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -0,0 +1,110 @@ +// Copyright 2016 The Gogs 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" +) + +// Milestone milestone is a collection of issues on one repository +type Milestone struct { + ID int64 `json:"id"` + Title string `json:"title"` + Description string `json:"description"` + State StateType `json:"state"` + OpenIssues int `json:"open_issues"` + ClosedIssues int `json:"closed_issues"` + Closed *time.Time `json:"closed_at"` + 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, 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 +func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, error) { + milestone := new(Milestone) + return milestone, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil, milestone) +} + +// CreateMilestoneOption options for creating a milestone +type CreateMilestoneOption struct { + Title string `json:"title"` + Description string `json:"description"` + State StateType `json:"state"` + Deadline *time.Time `json:"due_on"` +} + +// CreateMilestone create one milestone with options +func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + milestone := new(Milestone) + err = c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) + + // make creating closed milestones need gitea >= v1.13.0 + // this make it backwards compatible + if err == nil && opt.State == StateClosed && milestone.State != StateClosed { + closed := "closed" + return c.EditMilestone(owner, repo, milestone.ID, EditMilestoneOption{ + State: &closed, + }) + } + + return milestone, err +} + +// EditMilestoneOption options for editing a milestone +type EditMilestoneOption struct { + Title string `json:"title"` + Description *string `json:"description"` + State *string `json:"state"` + Deadline *time.Time `json:"due_on"` +} + +// EditMilestone modify milestone with options +func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + milestone := new(Milestone) + return milestone, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), milestone) +} + +// DeleteMilestone delete one milestone by milestone id +func (c *Client) DeleteMilestone(owner, repo string, id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_reaction.go b/vendor/code.gitea.io/sdk/gitea/issue_reaction.go new file mode 100644 index 000000000000..fb7d6d6cf708 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_reaction.go @@ -0,0 +1,98 @@ +// 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" +) + +// Reaction contain one reaction +type Reaction struct { + User *User `json:"user"` + Reaction string `json:"content"` + Created time.Time `json:"created_at"` +} + +// GetIssueReactions get a list reactions of an issue +func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + reactions := make([]*Reaction, 0, 10) + return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), nil, nil, &reactions) +} + +// GetIssueCommentReactions get a list of reactions from a comment of an issue +func (c *Client) GetIssueCommentReactions(owner, repo string, commentID int64) ([]*Reaction, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + reactions := make([]*Reaction, 0, 10) + return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), nil, nil, &reactions) +} + +// editReactionOption contain the reaction type +type editReactionOption struct { + Reaction string `json:"content"` +} + +// PostIssueReaction add a reaction to an issue +func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction string) (*Reaction, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + reactionResponse := new(Reaction) + body, err := json.Marshal(&editReactionOption{Reaction: reaction}) + if err != nil { + return nil, err + } + return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), + jsonHeader, bytes.NewReader(body), reactionResponse) +} + +// DeleteIssueReaction remove a reaction from an issue +func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction string) error { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return err + } + body, err := json.Marshal(&editReactionOption{Reaction: reaction}) + if err != nil { + return err + } + _, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body)) + return err +} + +// PostIssueCommentReaction add a reaction to a comment of an issue +func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Reaction, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + reactionResponse := new(Reaction) + body, err := json.Marshal(&editReactionOption{Reaction: reaction}) + if err != nil { + return nil, err + } + return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), + jsonHeader, bytes.NewReader(body), reactionResponse) +} + +// DeleteIssueCommentReaction remove a reaction from a comment of an issue +func (c *Client) DeleteIssueCommentReaction(owner, repo string, commentID int64, reaction string) error { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return err + } + // swagger:operation DELETE /repos/{owner}/{repo}/issues/comments/{id}/reactions issue issueDeleteCommentReaction + body, err := json.Marshal(&editReactionOption{Reaction: reaction}) + if err != nil { + return err + } + _, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), + jsonHeader, bytes.NewReader(body)) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go b/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go new file mode 100644 index 000000000000..8b8f178de5c3 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go @@ -0,0 +1,42 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" + "time" +) + +// StopWatch represents a running stopwatch of an issue / pr +type StopWatch struct { + Created time.Time `json:"created"` + IssueIndex int64 `json:"issue_index"` +} + +// GetMyStopwatches list all stopwatches +func (c *Client) GetMyStopwatches() ([]*StopWatch, error) { + stopwatches := make([]*StopWatch, 0, 1) + return stopwatches, c.getParsedResponse("GET", "/user/stopwatches", nil, nil, &stopwatches) +} + +// DeleteIssueStopwatch delete / cancel a specific stopwatch +func (c *Client) DeleteIssueStopwatch(owner, repo string, index int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/delete", owner, repo, index), nil, nil) + return err +} + +// StartIssueStopWatch starts a stopwatch for an existing issue for a given +// repository +func (c *Client) StartIssueStopWatch(owner, repo string, index int64) error { + _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/start", owner, repo, index), nil, nil) + return err +} + +// StopIssueStopWatch stops an existing stopwatch for an issue in a given +// repository +func (c *Client) StopIssueStopWatch(owner, repo string, index int64) error { + _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/stop", owner, repo, index), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_subscription.go b/vendor/code.gitea.io/sdk/gitea/issue_subscription.go new file mode 100644 index 000000000000..b7980cf9a100 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_subscription.go @@ -0,0 +1,82 @@ +// 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/http" +) + +// GetIssueSubscribers get list of users who subscribed on an issue +func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + subscribers := make([]*User, 0, 10) + return subscribers, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions", owner, repo, index), nil, nil, &subscribers) +} + +// AddIssueSubscription Subscribe user to issue +func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) error { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return err + } + 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 +func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) error { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return err + } + 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 +func (c *Client) IssueSubscribe(owner, repo string, index int64) error { + u, err := c.GetMyUserInfo() + if err != nil { + return err + } + return c.AddIssueSubscription(owner, repo, index, u.UserName) +} + +// IssueUnSubscribe unsubscribe current user from an issue +func (c *Client) IssueUnSubscribe(owner, repo string, index int64) error { + u, err := c.GetMyUserInfo() + if err != nil { + return err + } + return c.DeleteIssueSubscription(owner, repo, index, u.UserName) +} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go new file mode 100644 index 000000000000..51f1a99b66b6 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go @@ -0,0 +1,89 @@ +// Copyright 2017 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" +) + +// TrackedTime worked time for an issue / pr +type TrackedTime struct { + ID int64 `json:"id"` + Created time.Time `json:"created"` + // Time in seconds + Time int64 `json:"time"` + // deprecated (only for backwards compatibility) + UserID int64 `json:"user_id"` + UserName string `json:"user_name"` + // deprecated (only for backwards compatibility) + IssueID int64 `json:"issue_id"` + Issue *Issue `json:"issue"` +} + +// GetUserTrackedTimes list tracked times of a user +func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, error) { + times := make([]*TrackedTime, 0, 10) + return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times/%s", owner, repo, user), nil, nil, ×) +} + +// GetRepoTrackedTimes list tracked times of a repository +func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, error) { + times := make([]*TrackedTime, 0, 10) + return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, ×) +} + +// GetMyTrackedTimes list tracked times of the current user +func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, error) { + times := make([]*TrackedTime, 0, 10) + return times, c.getParsedResponse("GET", "/user/times", nil, nil, ×) +} + +// AddTimeOption options for adding time to an issue +type AddTimeOption struct { + // time in seconds + Time int64 `json:"time" binding:"Required"` + // optional + Created time.Time `json:"created"` + // optional + User string `json:"user_name"` +} + +// AddTime adds time to issue with the given index +func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + t := new(TrackedTime) + return t, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), + 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, ×) +} + +// 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) + return err +} + +// DeleteTime delete a specific tracked time by id of a single issue for a given repository +func (c *Client) DeleteTime(owner, repo string, index, timeID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/list_options.go b/vendor/code.gitea.io/sdk/gitea/list_options.go new file mode 100644 index 000000000000..d56c651b34e8 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/list_options.go @@ -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 + } +} diff --git a/vendor/code.gitea.io/sdk/gitea/notifications.go b/vendor/code.gitea.io/sdk/gitea/notifications.go new file mode 100644 index 000000000000..188de88c39b7 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/notifications.go @@ -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 +} diff --git a/vendor/code.gitea.io/sdk/gitea/oauth2.go b/vendor/code.gitea.io/sdk/gitea/oauth2.go new file mode 100644 index 000000000000..527535d046ab --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/oauth2.go @@ -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 +} diff --git a/vendor/code.gitea.io/sdk/gitea/org.go b/vendor/code.gitea.io/sdk/gitea/org.go new file mode 100644 index 000000000000..61ade3095c2c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org.go @@ -0,0 +1,98 @@ +// Copyright 2015 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// Organization represents an organization +type Organization struct { + ID int64 `json:"id"` + UserName string `json:"username"` + FullName string `json:"full_name"` + AvatarURL string `json:"avatar_url"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` + 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(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, 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 +func (c *Client) GetOrg(orgname string) (*Organization, error) { + org := new(Organization) + return org, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org) +} + +// CreateOrgOption options for creating an organization +type CreateOrgOption struct { + UserName string `json:"username"` + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` + // possible values are `public` (default), `limited` or `private` + // enum: public,limited,private + Visibility string `json:"visibility"` +} + +// CreateOrg creates an organization +func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + org := new(Organization) + return org, c.getParsedResponse("POST", "/orgs", jsonHeader, bytes.NewReader(body), org) +} + +// EditOrgOption options for editing an organization +type EditOrgOption struct { + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` + // possible values are `public`, `limited` or `private` + // enum: public,limited,private + Visibility string `json:"visibility"` +} + +// EditOrg modify one organization via options +func (c *Client) EditOrg(orgname string, opt EditOrgOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body)) + return err +} + +// DeleteOrg deletes an organization +func (c *Client) DeleteOrg(orgname string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/org_member.go b/vendor/code.gitea.io/sdk/gitea/org_member.go new file mode 100644 index 000000000000..9e1bf7768c92 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_member.go @@ -0,0 +1,98 @@ +// 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/http" + "net/url" +) + +// 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 +} + +// 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 + } + switch status { + case http.StatusNoContent: + return nil + case http.StatusNotFound: + return fmt.Errorf("forbidden") + default: + return fmt.Errorf("unexpected Status: %d", status) + } +} diff --git a/vendor/code.gitea.io/sdk/gitea/org_team.go b/vendor/code.gitea.io/sdk/gitea/org_team.go new file mode 100644 index 000000000000..4c786e3b8eb1 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_team.go @@ -0,0 +1,148 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// Team represents a team in an organization +type Team struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Organization *Organization `json:"organization"` + // enum: none,read,write,admin,owner + Permission string `json:"permission"` + // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] + 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, 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(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 +func (c *Client) GetTeam(id int64) (*Team, error) { + t := new(Team) + return t, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d", id), nil, nil, t) +} + +// CreateTeamOption options for creating a team +type CreateTeamOption struct { + Name string `json:"name"` + Description string `json:"description"` + // enum: read,write,admin + Permission string `json:"permission"` + // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] + Units []string `json:"units"` +} + +// CreateTeam creates a team for an organization +func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + t := new(Team) + return t, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/teams", org), jsonHeader, bytes.NewReader(body), t) +} + +// EditTeamOption options for editing a team +type EditTeamOption struct { + Name string `json:"name"` + Description string `json:"description"` + // enum: read,write,admin + Permission string `json:"permission"` + // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] + Units []string `json:"units"` +} + +// EditTeam edits a team of an organization +func (c *Client) EditTeam(id int64, opt EditTeamOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PATCH", fmt.Sprintf("/teams/%d", id), jsonHeader, bytes.NewReader(body)) + return err +} + +// DeleteTeam deletes a team of an organization +func (c *Client) DeleteTeam(id int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d", id), nil, nil) + 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, 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 +func (c *Client) GetTeamMember(id int64, user string) (*User, error) { + m := new(User) + return m, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil, m) +} + +// AddTeamMember adds a member to a team +func (c *Client) AddTeamMember(id int64, user string) error { + _, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) + return err +} + +// RemoveTeamMember removes a member from a team +func (c *Client) RemoveTeamMember(id int64, user string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) + 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, 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 +func (c *Client) AddTeamRepository(id int64, org, repo string) error { + _, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) + return err +} + +// RemoveTeamRepository removes a repository from a team +func (c *Client) RemoveTeamRepository(id int64, org, repo string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/org_type.go b/vendor/code.gitea.io/sdk/gitea/org_type.go new file mode 100644 index 000000000000..930be186a373 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_type.go @@ -0,0 +1,27 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +// VisibleType defines the visibility (Organization only) +type VisibleType int + +const ( + // VisibleTypePublic Visible for everyone + VisibleTypePublic VisibleType = iota + + // VisibleTypeLimited Visible for every connected user + VisibleTypeLimited + + // VisibleTypePrivate Visible only for organization's members + VisibleTypePrivate +) + +// ExtractKeysFromMapString provides a slice of keys from map +func ExtractKeysFromMapString(in map[string]VisibleType) (keys []string) { + for k := range in { + keys = append(keys, k) + } + return +} diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go new file mode 100644 index 000000000000..5005b18e587f --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -0,0 +1,196 @@ +// Copyright 2016 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" + "net/url" + "time" +) + +// PRBranchInfo information about a branch +type PRBranchInfo struct { + Name string `json:"label"` + Ref string `json:"ref"` + Sha string `json:"sha"` + RepoID int64 `json:"repo_id"` + Repository *Repository `json:"repo"` +} + +// PullRequest represents a pull request +type PullRequest struct { + ID int64 `json:"id"` + URL string `json:"url"` + Index int64 `json:"number"` + Poster *User `json:"user"` + Title string `json:"title"` + Body string `json:"body"` + Labels []*Label `json:"labels"` + Milestone *Milestone `json:"milestone"` + Assignee *User `json:"assignee"` + Assignees []*User `json:"assignees"` + State StateType `json:"state"` + Comments int `json:"comments"` + + HTMLURL string `json:"html_url"` + DiffURL string `json:"diff_url"` + PatchURL string `json:"patch_url"` + + Mergeable bool `json:"mergeable"` + HasMerged bool `json:"merged"` + Merged *time.Time `json:"merged_at"` + MergedCommitID *string `json:"merge_commit_sha"` + MergedBy *User `json:"merged_by"` + + Base *PRBranchInfo `json:"base"` + Head *PRBranchInfo `json:"head"` + MergeBase string `json:"merge_base"` + + Deadline *time.Time `json:"due_date"` + Created *time.Time `json:"created_at"` + Updated *time.Time `json:"updated_at"` + Closed *time.Time `json:"closed_at"` +} + +// ListPullRequestsOptions options for listing pull requests +type ListPullRequestsOptions struct { + ListOptions + State StateType `json:"state"` + // oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority + Sort string + Milestone int64 +} + +// 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", string(opt.State)) + } + if len(opt.Sort) > 0 { + query.Add("sort", opt.Sort) + } + if opt.Milestone > 0 { + query.Add("milestone", fmt.Sprintf("%d", opt.Milestone)) + } + 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) +} + +// GetPullRequest get information of one PR +func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest, error) { + pr := new(PullRequest) + return pr, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), nil, nil, pr) +} + +// CreatePullRequestOption options when creating a pull request +type CreatePullRequestOption struct { + Head string `json:"head"` + Base string `json:"base"` + Title string `json:"title"` + Body string `json:"body"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + Deadline *time.Time `json:"due_date"` +} + +// CreatePullRequest create pull request with options +func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOption) (*PullRequest, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + pr := new(PullRequest) + return pr, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), + jsonHeader, bytes.NewReader(body), pr) +} + +// EditPullRequestOption options when modify pull request +type EditPullRequestOption struct { + Title string `json:"title"` + Body string `json:"body"` + Base string `json:"base"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + State *StateType `json:"state"` + Deadline *time.Time `json:"due_date"` +} + +// EditPullRequest modify pull request with PR id and options +func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + pr := new(PullRequest) + return pr, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), + jsonHeader, bytes.NewReader(body), pr) +} + +// MergePullRequestOption options when merging a pull request +type MergePullRequestOption struct { + 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 + } + status, err := c.getStatusCode("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), jsonHeader, bytes.NewReader(body)) + if err != nil { + return false, err + } + return status == 200, nil +} + +// IsPullRequestMerged test if one PR is merged to one repository +func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, error) { + statusCode, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) + + if err != nil { + return false, err + } + + return statusCode == 204, nil +} diff --git a/vendor/code.gitea.io/sdk/gitea/pull_review.go b/vendor/code.gitea.io/sdk/gitea/pull_review.go new file mode 100644 index 000000000000..9ff708a12cf3 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/pull_review.go @@ -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) +} diff --git a/vendor/code.gitea.io/sdk/gitea/release.go b/vendor/code.gitea.io/sdk/gitea/release.go new file mode 100644 index 000000000000..fe5c023de031 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -0,0 +1,108 @@ +// Copyright 2016 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" +) + +// Release represents a repository release +type Release struct { + ID int64 `json:"id"` + TagName string `json:"tag_name"` + Target string `json:"target_commitish"` + Title string `json:"name"` + Note string `json:"body"` + URL string `json:"url"` + TarURL string `json:"tarball_url"` + ZipURL string `json:"zipball_url"` + IsDraft bool `json:"draft"` + IsPrerelease bool `json:"prerelease"` + CreatedAt time.Time `json:"created_at"` + PublishedAt time.Time `json:"published_at"` + Publisher *User `json:"author"` + 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, opt ListReleasesOptions) ([]*Release, error) { + opt.setDefaults() + releases := make([]*Release, 0, opt.PageSize) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases?%s", user, repo, opt.getURLQuery().Encode()), + nil, nil, &releases) + return releases, err +} + +// GetRelease get a release of a repository +func (c *Client) GetRelease(user, repo string, id int64) (*Release, error) { + r := new(Release) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), + nil, nil, &r) + return r, err +} + +// CreateReleaseOption options when creating a release +type CreateReleaseOption struct { + TagName string `json:"tag_name"` + Target string `json:"target_commitish"` + Title string `json:"name"` + Note string `json:"body"` + IsDraft bool `json:"draft"` + IsPrerelease bool `json:"prerelease"` +} + +// CreateRelease create a release +func (c *Client) CreateRelease(user, repo string, form CreateReleaseOption) (*Release, error) { + body, err := json.Marshal(form) + if err != nil { + return nil, err + } + r := new(Release) + err = c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/releases", user, repo), + jsonHeader, bytes.NewReader(body), r) + return r, err +} + +// EditReleaseOption options when editing a release +type EditReleaseOption struct { + TagName string `json:"tag_name"` + Target string `json:"target_commitish"` + Title string `json:"name"` + Note string `json:"body"` + IsDraft *bool `json:"draft"` + IsPrerelease *bool `json:"prerelease"` +} + +// EditRelease edit a release +func (c *Client) EditRelease(user, repo string, id int64, form EditReleaseOption) (*Release, error) { + body, err := json.Marshal(form) + if err != nil { + return nil, err + } + r := new(Release) + err = c.getParsedResponse("PATCH", + fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), + jsonHeader, bytes.NewReader(body), r) + return r, err +} + +// DeleteRelease delete a release from a repository +func (c *Client) DeleteRelease(user, repo string, id int64) error { + _, err := c.getResponse("DELETE", + fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), + nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo.go b/vendor/code.gitea.io/sdk/gitea/repo.go new file mode 100644 index 000000000000..80f24b889997 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -0,0 +1,290 @@ +// Copyright 2014 The Gogs 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" +) + +// Permission represents a set of permissions +type Permission struct { + Admin bool `json:"admin"` + Push bool `json:"push"` + Pull bool `json:"pull"` +} + +// Repository represents a repository +type Repository struct { + ID int64 `json:"id"` + Owner *User `json:"owner"` + Name string `json:"name"` + FullName string `json:"full_name"` + Description string `json:"description"` + Empty bool `json:"empty"` + Private bool `json:"private"` + Fork bool `json:"fork"` + Parent *Repository `json:"parent"` + Mirror bool `json:"mirror"` + Size int `json:"size"` + HTMLURL string `json:"html_url"` + SSHURL string `json:"ssh_url"` + CloneURL string `json:"clone_url"` + OriginalURL string `json:"original_url"` + Website string `json:"website"` + Stars int `json:"stars_count"` + Forks int `json:"forks_count"` + Watchers int `json:"watchers_count"` + OpenIssues int `json:"open_issues_count"` + DefaultBranch string `json:"default_branch"` + Archived bool `json:"archived"` + Created time.Time `json:"created_at"` + Updated time.Time `json:"updated_at"` + Permissions *Permission `json:"permissions,omitempty"` + HasIssues bool `json:"has_issues"` + HasWiki bool `json:"has_wiki"` + HasPullRequests bool `json:"has_pull_requests"` + IgnoreWhitespaceConflicts bool `json:"ignore_whitespace_conflicts"` + AllowMerge bool `json:"allow_merge_commits"` + AllowRebase bool `json:"allow_rebase"` + AllowRebaseMerge bool `json:"allow_rebase_explicit"` + AllowSquash bool `json:"allow_squash_merge"` + 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(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, 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, 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 +type CreateRepoOption struct { + // Name of the repository to create + // + Name string `json:"name"` + // Description of the repository to create + Description string `json:"description"` + // Whether the repository is private + Private bool `json:"private"` + // Issue Label set to use + IssueLabels string `json:"issue_labels"` + // Whether the repository should be auto-intialized? + AutoInit bool `json:"auto_init"` + // Gitignores to use + Gitignores string `json:"gitignores"` + // License to use + 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. +func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + repo := new(Repository) + return repo, c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo) +} + +// CreateOrgRepo creates an organization repository for authenticated user. +func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + repo := new(Repository) + return repo, c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo) +} + +// GetRepo returns information of a repository of given owner. +func (c *Client) GetRepo(owner, reponame string) (*Repository, error) { + repo := new(Repository) + return repo, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo) +} + +// EditRepoOption options when editing a repository's properties +type EditRepoOption struct { + // name of the repository + Name *string `json:"name,omitempty"` + // a short description of the repository. + Description *string `json:"description,omitempty"` + // a URL with more information about the repository. + Website *string `json:"website,omitempty"` + // either `true` to make the repository private or `false` to make it public. + // Note: you will get a 422 error if the organization restricts changing repository visibility to organization + // owners and a non-owner tries to change the value of private. + Private *bool `json:"private,omitempty"` + // either `true` to enable issues for this repository or `false` to disable them. + HasIssues *bool `json:"has_issues,omitempty"` + // either `true` to enable the wiki for this repository or `false` to disable it. + HasWiki *bool `json:"has_wiki,omitempty"` + // sets the default branch for this repository. + DefaultBranch *string `json:"default_branch,omitempty"` + // either `true` to allow pull requests, or `false` to prevent pull request. + HasPullRequests *bool `json:"has_pull_requests,omitempty"` + // either `true` to ignore whitespace for conflicts, or `false` to not ignore whitespace. `has_pull_requests` must be `true`. + IgnoreWhitespaceConflicts *bool `json:"ignore_whitespace_conflicts,omitempty"` + // either `true` to allow merging pull requests with a merge commit, or `false` to prevent merging pull requests with merge commits. `has_pull_requests` must be `true`. + AllowMerge *bool `json:"allow_merge_commits,omitempty"` + // either `true` to allow rebase-merging pull requests, or `false` to prevent rebase-merging. `has_pull_requests` must be `true`. + AllowRebase *bool `json:"allow_rebase,omitempty"` + // either `true` to allow rebase with explicit merge commits (--no-ff), or `false` to prevent rebase with explicit merge commits. `has_pull_requests` must be `true`. + AllowRebaseMerge *bool `json:"allow_rebase_explicit,omitempty"` + // either `true` to allow squash-merging pull requests, or `false` to prevent squash-merging. `has_pull_requests` must be `true`. + AllowSquash *bool `json:"allow_squash_merge,omitempty"` + // set to `true` to archive this repository. + Archived *bool `json:"archived,omitempty"` +} + +// EditRepo edit the properties of a repository +func (c *Client) EditRepo(owner, reponame string, opt EditRepoOption) (*Repository, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + repo := new(Repository) + return repo, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s", owner, reponame), jsonHeader, bytes.NewReader(body), repo) +} + +// DeleteRepo deletes a repository of user or organization. +func (c *Client) DeleteRepo(owner, repo string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil) + return err +} + +// MigrateRepoOption options for migrating a repository from an external service +type MigrateRepoOption struct { + CloneAddr string `json:"clone_addr"` + AuthUsername string `json:"auth_username"` + AuthPassword string `json:"auth_password"` + UID int `json:"uid"` + RepoName string `json:"repo_name"` + Mirror bool `json:"mirror"` + Private bool `json:"private"` + Description string `json:"description"` +} + +// MigrateRepo migrates a repository from other Git hosting sources for the +// authenticated user. +// +// To migrate a repository for a organization, the authenticated user must be a +// owner of the specified organization. +func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + repo := new(Repository) + return repo, c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo) +} + +// MirrorSync adds a mirrored repository to the mirror sync queue. +func (c *Client) MirrorSync(owner, repo string) error { + _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch.go b/vendor/code.gitea.io/sdk/gitea/repo_branch.go new file mode 100644 index 000000000000..084a6ce7c3e0 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch.go @@ -0,0 +1,91 @@ +// 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 ( + "fmt" + "time" +) + +// PayloadUser represents the author or committer of a commit +type PayloadUser struct { + // Full name of the commit author + Name string `json:"name"` + Email string `json:"email"` + UserName string `json:"username"` +} + +// FIXME: consider using same format as API when commits API are added. +// applies to PayloadCommit and PayloadCommitVerification + +// PayloadCommit represents a commit +type PayloadCommit struct { + // sha1 hash of the commit + ID string `json:"id"` + Message string `json:"message"` + URL string `json:"url"` + Author *PayloadUser `json:"author"` + Committer *PayloadUser `json:"committer"` + Verification *PayloadCommitVerification `json:"verification"` + Timestamp time.Time `json:"timestamp"` + Added []string `json:"added"` + Removed []string `json:"removed"` + Modified []string `json:"modified"` +} + +// PayloadCommitVerification represents the GPG verification of a commit +type PayloadCommitVerification struct { + Verified bool `json:"verified"` + Reason string `json:"reason"` + Signature string `json:"signature"` + Payload string `json:"payload"` +} + +// Branch represents a repository branch +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, 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) + 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 +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go new file mode 100644 index 000000000000..b7ef96c74267 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go @@ -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 +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go new file mode 100644 index 000000000000..e13ccdbd3876 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -0,0 +1,59 @@ +// Copyright 2016 The Gogs 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" +) + +// 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, 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) +} + +// 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) + if err != nil { + return false, err + } + if status == 204 { + return true, nil + } + return false, nil +} + +// AddCollaboratorOption options when adding a user as a collaborator of a repository +type AddCollaboratorOption struct { + Permission *string `json:"permission"` +} + +// AddCollaborator add some user as a collaborator of a repository +func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), jsonHeader, bytes.NewReader(body)) + return err +} + +// 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) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_commit.go b/vendor/code.gitea.io/sdk/gitea/repo_commit.go new file mode 100644 index 000000000000..82ef3fa97e11 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_commit.go @@ -0,0 +1,86 @@ +// Copyright 2018 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" + "net/url" + "time" +) + +// Identity for a person's identity like an author or committer +type Identity struct { + Name string `json:"name"` + Email string `json:"email"` +} + +// CommitMeta contains meta information of a commit in terms of API. +type CommitMeta struct { + URL string `json:"url"` + SHA string `json:"sha"` +} + +// CommitUser contains information of a user in the context of a commit. +type CommitUser struct { + Identity + Date string `json:"date"` +} + +// RepoCommit contains information of a commit in the context of a repository. +type RepoCommit struct { + URL string `json:"url"` + Author *CommitUser `json:"author"` + Committer *CommitUser `json:"committer"` + Message string `json:"message"` + Tree *CommitMeta `json:"tree"` +} + +// Commit contains information generated from a Git commit. +type Commit struct { + *CommitMeta + HTMLURL string `json:"html_url"` + RepoCommit *RepoCommit `json:"commit"` + Author *User `json:"author"` + Committer *User `json:"committer"` + 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) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go new file mode 100644 index 000000000000..18818592d7b6 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_file.go @@ -0,0 +1,192 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +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) { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return nil, err + } + + 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) { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return nil, err + } + + 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 { + var err error + if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { + return err + } + + 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 +} + +func (c *Client) setDefaultBranchForOldVersions(owner, repo, branch string) (string, error) { + if len(branch) == 0 { + // Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + r, err := c.GetRepo(owner, repo) + if err != nil { + return "", err + } + return r.DefaultBranch, nil + } + } + return branch, nil +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_key.go b/vendor/code.gitea.io/sdk/gitea/repo_key.go new file mode 100644 index 000000000000..041df5da8f34 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_key.go @@ -0,0 +1,76 @@ +// Copyright 2015 The Gogs 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" +) + +// DeployKey a deploy key +type DeployKey struct { + ID int64 `json:"id"` + KeyID int64 `json:"key_id"` + Key string `json:"key"` + URL string `json:"url"` + Title string `json:"title"` + Fingerprint string `json:"fingerprint"` + Created time.Time `json:"created_at"` + ReadOnly bool `json:"read_only"` + 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, 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 +func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, error) { + key := new(DeployKey) + return key, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key) +} + +// CreateDeployKey options when create one deploy key +func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + key := new(DeployKey) + return key, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key) +} + +// DeleteDeployKey delete deploy key with key id +func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_refs.go b/vendor/code.gitea.io/sdk/gitea/repo_refs.go new file mode 100644 index 000000000000..b946a100265b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_refs.go @@ -0,0 +1,69 @@ +// Copyright 2018 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 ( + "encoding/json" + "errors" + "fmt" + "strings" +) + +// Reference represents a Git reference. +type Reference struct { + Ref string `json:"ref"` + URL string `json:"url"` + Object *GitObject `json:"object"` +} + +// GitObject represents a Git object. +type GitObject struct { + Type string `json:"type"` + SHA string `json:"sha"` + URL string `json:"url"` +} + +// GetRepoRef get one ref's information of one repository +func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, error) { + ref = strings.TrimPrefix(ref, "refs/") + r := new(Reference) + err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r) + if _, ok := err.(*json.UnmarshalTypeError); ok { + // Multiple refs + return nil, errors.New("no exact match found for this ref") + } else if err != nil { + return nil, err + } + + return r, nil +} + +// GetRepoRefs get list of ref's information of one repository +func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, error) { + ref = strings.TrimPrefix(ref, "refs/") + resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil) + if err != nil { + return nil, err + } + + // Attempt to unmarshal single returned ref. + r := new(Reference) + refErr := json.Unmarshal(resp, r) + if refErr == nil { + return []*Reference{r}, nil + } + + // Attempt to unmarshal multiple refs. + var rs []*Reference + refsErr := json.Unmarshal(resp, &rs) + if refsErr == nil { + if len(rs) == 0 { + return nil, errors.New("unexpected response: an array of refs with length 0") + } + return rs, nil + } + + return nil, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_tag.go b/vendor/code.gitea.io/sdk/gitea/repo_tag.go new file mode 100644 index 000000000000..b64d90b81e78 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_tag.go @@ -0,0 +1,30 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" +) + +// Tag represents a repository tag +type Tag struct { + Name string `json:"name"` + ID string `json:"id"` + Commit *CommitMeta `json:"commit"` + ZipballURL string `json:"zipball_url"` + TarballURL string `json:"tarball_url"` +} + +// 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) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_topics.go b/vendor/code.gitea.io/sdk/gitea/repo_topics.go new file mode 100644 index 000000000000..8d90e2691ef1 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_topics.go @@ -0,0 +1,58 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// 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, 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 []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 +} + +// AddRepoTopic adds a topic to a repo's topics list +func (c *Client) AddRepoTopic(user, repo, topic string) error { + _, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) + return err +} + +// DeleteRepoTopic deletes a topic from repo's topics list +func (c *Client) DeleteRepoTopic(user, repo, topic string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_transfer.go b/vendor/code.gitea.io/sdk/gitea/repo_transfer.go new file mode 100644 index 000000000000..1b61e2f38f8e --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_transfer.go @@ -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) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_tree.go b/vendor/code.gitea.io/sdk/gitea/repo_tree.go new file mode 100644 index 000000000000..d258bdfff282 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_tree.go @@ -0,0 +1,40 @@ +// Copyright 2018 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" +) + +// GitEntry represents a git tree +type GitEntry struct { + Path string `json:"path"` + Mode string `json:"mode"` + Type string `json:"type"` + Size int64 `json:"size"` + SHA string `json:"sha"` + URL string `json:"url"` +} + +// GitTreeResponse returns a git tree +type GitTreeResponse struct { + SHA string `json:"sha"` + URL string `json:"url"` + Entries []GitEntry `json:"tree"` + Truncated bool `json:"truncated"` + Page int `json:"page"` + TotalCount int `json:"total_count"` +} + +// 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) { + trees := new(GitTreeResponse) + var path = fmt.Sprintf("/repos/%s/%s/git/trees/%s", user, repo, ref) + if recursive { + path += "?recursive=1" + } + return trees, c.getParsedResponse("GET", path, nil, nil, trees) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go new file mode 100644 index 000000000000..c8ed3a198e82 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_watch.go @@ -0,0 +1,73 @@ +// Copyright 2017 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/http" + "time" +) + +// WatchInfo represents an API watch status of one repository +type WatchInfo struct { + Subscribed bool `json:"subscribed"` + Ignored bool `json:"ignored"` + Reason interface{} `json:"reason"` + CreatedAt time.Time `json:"created_at"` + URL string `json:"url"` + RepositoryURL string `json:"repository_url"` +} + +// GetWatchedRepos list all the watched repos of user +func (c *Client) GetWatchedRepos(user string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + 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(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 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) +} diff --git a/vendor/code.gitea.io/sdk/gitea/status.go b/vendor/code.gitea.io/sdk/gitea/status.go new file mode 100644 index 000000000000..f072cf89d8a5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/status.go @@ -0,0 +1,89 @@ +// Copyright 2017 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" +) + +// StatusState holds the state of a Status +// It can be "pending", "success", "error", "failure", and "warning" +type StatusState string + +const ( + // StatusPending is for when the Status is Pending + StatusPending StatusState = "pending" + // StatusSuccess is for when the Status is Success + StatusSuccess StatusState = "success" + // StatusError is for when the Status is Error + StatusError StatusState = "error" + // StatusFailure is for when the Status is Failure + StatusFailure StatusState = "failure" + // StatusWarning is for when the Status is Warning + StatusWarning StatusState = "warning" +) + +// Status holds a single Status of a single Commit +type Status struct { + ID int64 `json:"id"` + State StatusState `json:"status"` + TargetURL string `json:"target_url"` + Description string `json:"description"` + URL string `json:"url"` + Context string `json:"context"` + Creator *User `json:"creator"` + Created time.Time `json:"created_at"` + Updated time.Time `json:"updated_at"` +} + +// CreateStatusOption holds the information needed to create a new Status for a Commit +type CreateStatusOption struct { + State StatusState `json:"state"` + TargetURL string `json:"target_url"` + Description string `json:"description"` + Context string `json:"context"` +} + +// CreateStatus creates a new Status for a given Commit +func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { + body, err := json.Marshal(&opts) + if err != nil { + return nil, err + } + status := new(Status) + return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status) +} + +// ListStatusesOption options for listing a repository's commit's statuses +type ListStatusesOption struct { + ListOptions +} + +// ListStatuses returns all statuses for a given Commit +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 +type CombinedStatus struct { + State StatusState `json:"state"` + SHA string `json:"sha"` + TotalCount int `json:"total_count"` + Statuses []*Status `json:"statuses"` + Repository *Repository `json:"repository"` + CommitURL string `json:"commit_url"` + URL string `json:"url"` +} + +// GetCombinedStatus returns the CombinedStatus for a given Commit +func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { + status := new(CombinedStatus) + return status, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, sha), nil, nil, status) +} diff --git a/vendor/code.gitea.io/sdk/gitea/user.go b/vendor/code.gitea.io/sdk/gitea/user.go new file mode 100644 index 000000000000..2433474369c9 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user.go @@ -0,0 +1,43 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" + "time" +) + +// User represents a user +type User struct { + // the user's id + ID int64 `json:"id"` + // the user's username + UserName string `json:"login"` + // the user's full name + FullName string `json:"full_name"` + Email string `json:"email"` + // URL to the user's avatar + AvatarURL string `json:"avatar_url"` + // User locale + Language string `json:"language"` + // Is the user an administrator + IsAdmin bool `json:"is_admin"` + LastLogin time.Time `json:"last_login,omitempty"` + Created time.Time `json:"created,omitempty"` +} + +// GetUserInfo get user info by user's name +func (c *Client) GetUserInfo(user string) (*User, error) { + u := new(User) + err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u) + return u, err +} + +// GetMyUserInfo get user info of current user +func (c *Client) GetMyUserInfo() (*User, error) { + u := new(User) + err := c.getParsedResponse("GET", "/user", nil, nil, u) + return u, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_app.go b/vendor/code.gitea.io/sdk/gitea/user_app.go new file mode 100644 index 000000000000..2205371e68ee --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_app.go @@ -0,0 +1,62 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2019 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// AccessToken represents an API access token. +type AccessToken struct { + ID int64 `json:"id"` + Name string `json:"name"` + Token string `json:"sha1"` + TokenLastEight string `json:"token_last_eight"` +} + +// 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 +type CreateAccessTokenOption struct { + Name string `json:"name"` +} + +// CreateAccessToken create one access token with options +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", c.username), jsonHeader, bytes.NewReader(body), t) +} + +// DeleteAccessToken delete token with key id +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 +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_email.go b/vendor/code.gitea.io/sdk/gitea/user_email.go new file mode 100644 index 000000000000..5cb4721f63b5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_email.go @@ -0,0 +1,62 @@ +// Copyright 2015 The Gogs 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" +) + +// Email an email address belonging to a user +type Email struct { + Email string `json:"email"` + Verified bool `json:"verified"` + 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(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 +type CreateEmailOption struct { + // email addresses to add + Emails []string `json:"emails"` +} + +// AddEmail add one email to current user with options +func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + emails := make([]*Email, 0, 3) + return emails, c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), &emails) +} + +// DeleteEmailOption options when deleting email addresses +type DeleteEmailOption struct { + // email addresses to delete + Emails []string `json:"emails"` +} + +// DeleteEmail delete one email of current users' +func (c *Client) DeleteEmail(opt DeleteEmailOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body)) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_follow.go b/vendor/code.gitea.io/sdk/gitea/user_follow.go new file mode 100644 index 000000000000..fdc53eff8053 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_follow.go @@ -0,0 +1,69 @@ +// Copyright 2015 The Gogs 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" + +// ListFollowersOptions options for listing followers +type ListFollowersOptions struct { + ListOptions +} + +// ListMyFollowers list all the followers of current user +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, 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(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, 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 +func (c *Client) IsFollowing(target string) bool { + _, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil) + return err == nil +} + +// IsUserFollowing if the user followed the target +func (c *Client) IsUserFollowing(user, target string) bool { + _, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil) + return err == nil +} + +// Follow set current user follow the target +func (c *Client) Follow(target string) error { + _, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil) + return err +} + +// Unfollow set current user unfollow the target +func (c *Client) Unfollow(target string) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go new file mode 100644 index 000000000000..026cb1ae8cae --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go @@ -0,0 +1,82 @@ +// Copyright 2017 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" +) + +// GPGKey a user GPG key to sign commit and tag in repository +type GPGKey struct { + ID int64 `json:"id"` + PrimaryKeyID string `json:"primary_key_id"` + KeyID string `json:"key_id"` + PublicKey string `json:"public_key"` + Emails []*GPGKeyEmail `json:"emails"` + SubsKey []*GPGKey `json:"subkeys"` + CanSign bool `json:"can_sign"` + CanEncryptComms bool `json:"can_encrypt_comms"` + CanEncryptStorage bool `json:"can_encrypt_storage"` + CanCertify bool `json:"can_certify"` + Created time.Time `json:"created_at,omitempty"` + Expires time.Time `json:"expires_at,omitempty"` +} + +// GPGKeyEmail an email attached to a GPGKey +type GPGKeyEmail struct { + Email string `json:"email"` + 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, 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(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 +func (c *Client) GetGPGKey(keyID int64) (*GPGKey, error) { + key := new(GPGKey) + return key, c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil, &key) +} + +// CreateGPGKeyOption options create user GPG key +type CreateGPGKeyOption struct { + // An armored GPG key to add + // + ArmoredKey string `json:"armored_public_key"` +} + +// CreateGPGKey create GPG key with options +func (c *Client) CreateGPGKey(opt CreateGPGKeyOption) (*GPGKey, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + key := new(GPGKey) + return key, c.getParsedResponse("POST", "/user/gpg_keys", jsonHeader, bytes.NewReader(body), key) +} + +// DeleteGPGKey delete GPG key with key id +func (c *Client) DeleteGPGKey(keyID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_key.go b/vendor/code.gitea.io/sdk/gitea/user_key.go new file mode 100644 index 000000000000..6c71487585df --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_key.go @@ -0,0 +1,76 @@ +// Copyright 2015 The Gogs 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" +) + +// PublicKey publickey is a user key to push code to repository +type PublicKey struct { + ID int64 `json:"id"` + Key string `json:"key"` + URL string `json:"url,omitempty"` + Title string `json:"title,omitempty"` + Fingerprint string `json:"fingerprint,omitempty"` + Created time.Time `json:"created_at,omitempty"` + Owner *User `json:"user,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + 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, 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(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 +func (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) { + key := new(PublicKey) + return key, c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key) +} + +// CreateKeyOption options when creating a key +type CreateKeyOption struct { + // Title of the key to add + Title string `json:"title"` + // An armored SSH key to add + Key string `json:"key"` + // Describe if the key has only read access or read/write + ReadOnly bool `json:"read_only"` +} + +// CreatePublicKey create public key with options +func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + key := new(PublicKey) + return key, c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key) +} + +// DeletePublicKey delete public key with key id +func (c *Client) DeletePublicKey(keyID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/user_search.go b/vendor/code.gitea.io/sdk/gitea/user_search.go new file mode 100644 index 000000000000..5e098211fb53 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_search.go @@ -0,0 +1,44 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" + "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(opt SearchUsersOption) ([]*User, error) { + link, _ := url.Parse("/users/search") + link.RawQuery = opt.QueryEncode() + resp := new(searchUsersResponse) + err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) + return resp.Users, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/version.go b/vendor/code.gitea.io/sdk/gitea/version.go new file mode 100644 index 000000000000..b0f1c7b09e83 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/version.go @@ -0,0 +1,57 @@ +// 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" + + "github.com/hashicorp/go-version" +) + +// ServerVersion returns the version of the server +func (c *Client) ServerVersion() (string, error) { + var v = struct { + Version string `json:"version"` + }{} + return v.Version, c.getParsedResponse("GET", "/version", nil, nil, &v) +} + +// CheckServerVersionConstraint validates that the login's server satisfies a +// given version constraint such as ">= 1.11.0+dev" +func (c *Client) CheckServerVersionConstraint(constraint string) error { + c.versionLock.RLock() + if c.serverVersion == nil { + c.versionLock.RUnlock() + if err := c.loadClientServerVersion(); err != nil { + return err + } + } else { + c.versionLock.RUnlock() + } + + check, err := version.NewConstraint(constraint) + if err != nil { + return err + } + if !check.Check(c.serverVersion) { + return fmt.Errorf("gitea server at %s does not satisfy version constraint %s", c.url, constraint) + } + return nil +} + +// loadClientServerVersion init the serverVersion variable +func (c *Client) loadClientServerVersion() error { + c.versionLock.Lock() + defer c.versionLock.Unlock() + + raw, err := c.ServerVersion() + if err != nil { + return err + } + if c.serverVersion, err = version.NewVersion(raw); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/hashicorp/go-version/.travis.yml b/vendor/github.com/hashicorp/go-version/.travis.yml new file mode 100644 index 000000000000..01c5dc219afa --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - 1.2 + - 1.3 + - 1.4 + - 1.9 + - "1.10" + - 1.11 + - 1.12 + +script: + - go test diff --git a/vendor/github.com/hashicorp/go-version/LICENSE b/vendor/github.com/hashicorp/go-version/LICENSE new file mode 100644 index 000000000000..c33dcc7c928c --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md new file mode 100644 index 000000000000..6f3a15ce7721 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -0,0 +1,65 @@ +# Versioning Library for Go +[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version) + +go-version is a library for parsing versions and version constraints, +and verifying versions against a set of constraints. go-version +can sort a collection of versions properly, handles prerelease/beta +versions, can increment versions, etc. + +Versions used with go-version must follow [SemVer](http://semver.org/). + +## Installation and Usage + +Package documentation can be found on +[GoDoc](http://godoc.org/github.com/hashicorp/go-version). + +Installation can be done with a normal `go get`: + +``` +$ go get github.com/hashicorp/go-version +``` + +#### Version Parsing and Comparison + +```go +v1, err := version.NewVersion("1.2") +v2, err := version.NewVersion("1.5+metadata") + +// Comparison example. There is also GreaterThan, Equal, and just +// a simple Compare that returns an int allowing easy >=, <=, etc. +if v1.LessThan(v2) { + fmt.Printf("%s is less than %s", v1, v2) +} +``` + +#### Version Constraints + +```go +v1, err := version.NewVersion("1.2") + +// Constraints example. +constraints, err := version.NewConstraint(">= 1.0, < 1.4") +if constraints.Check(v1) { + fmt.Printf("%s satisfies constraints %s", v1, constraints) +} +``` + +#### Version Sorting + +```go +versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"} +versions := make([]*version.Version, len(versionsRaw)) +for i, raw := range versionsRaw { + v, _ := version.NewVersion(raw) + versions[i] = v +} + +// After this, the versions are properly sorted +sort.Sort(version.Collection(versions)) +``` + +## Issues and Contributing + +If you find an issue with this library, please report an issue. If you'd +like, we welcome any contributions. Fork this library and submit a pull +request. diff --git a/vendor/github.com/hashicorp/go-version/constraint.go b/vendor/github.com/hashicorp/go-version/constraint.go new file mode 100644 index 000000000000..d055759611c8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/constraint.go @@ -0,0 +1,204 @@ +package version + +import ( + "fmt" + "reflect" + "regexp" + "strings" +) + +// Constraint represents a single constraint for a version, such as +// ">= 1.0". +type Constraint struct { + f constraintFunc + check *Version + original string +} + +// Constraints is a slice of constraints. We make a custom type so that +// we can add methods to it. +type Constraints []*Constraint + +type constraintFunc func(v, c *Version) bool + +var constraintOperators map[string]constraintFunc + +var constraintRegexp *regexp.Regexp + +func init() { + constraintOperators = map[string]constraintFunc{ + "": constraintEqual, + "=": constraintEqual, + "!=": constraintNotEqual, + ">": constraintGreaterThan, + "<": constraintLessThan, + ">=": constraintGreaterThanEqual, + "<=": constraintLessThanEqual, + "~>": constraintPessimistic, + } + + ops := make([]string, 0, len(constraintOperators)) + for k := range constraintOperators { + ops = append(ops, regexp.QuoteMeta(k)) + } + + constraintRegexp = regexp.MustCompile(fmt.Sprintf( + `^\s*(%s)\s*(%s)\s*$`, + strings.Join(ops, "|"), + VersionRegexpRaw)) +} + +// NewConstraint will parse one or more constraints from the given +// constraint string. The string must be a comma-separated list of +// constraints. +func NewConstraint(v string) (Constraints, error) { + vs := strings.Split(v, ",") + result := make([]*Constraint, len(vs)) + for i, single := range vs { + c, err := parseSingle(single) + if err != nil { + return nil, err + } + + result[i] = c + } + + return Constraints(result), nil +} + +// Check tests if a version satisfies all the constraints. +func (cs Constraints) Check(v *Version) bool { + for _, c := range cs { + if !c.Check(v) { + return false + } + } + + return true +} + +// Returns the string format of the constraints +func (cs Constraints) String() string { + csStr := make([]string, len(cs)) + for i, c := range cs { + csStr[i] = c.String() + } + + return strings.Join(csStr, ",") +} + +// Check tests if a constraint is validated by the given version. +func (c *Constraint) Check(v *Version) bool { + return c.f(v, c.check) +} + +func (c *Constraint) String() string { + return c.original +} + +func parseSingle(v string) (*Constraint, error) { + matches := constraintRegexp.FindStringSubmatch(v) + if matches == nil { + return nil, fmt.Errorf("Malformed constraint: %s", v) + } + + check, err := NewVersion(matches[2]) + if err != nil { + return nil, err + } + + return &Constraint{ + f: constraintOperators[matches[1]], + check: check, + original: v, + }, nil +} + +func prereleaseCheck(v, c *Version) bool { + switch vPre, cPre := v.Prerelease() != "", c.Prerelease() != ""; { + case cPre && vPre: + // A constraint with a pre-release can only match a pre-release version + // with the same base segments. + return reflect.DeepEqual(c.Segments64(), v.Segments64()) + + case !cPre && vPre: + // A constraint without a pre-release can only match a version without a + // pre-release. + return false + + case cPre && !vPre: + // OK, except with the pessimistic operator + case !cPre && !vPre: + // OK + } + return true +} + +//------------------------------------------------------------------- +// Constraint functions +//------------------------------------------------------------------- + +func constraintEqual(v, c *Version) bool { + return v.Equal(c) +} + +func constraintNotEqual(v, c *Version) bool { + return !v.Equal(c) +} + +func constraintGreaterThan(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) == 1 +} + +func constraintLessThan(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) == -1 +} + +func constraintGreaterThanEqual(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) >= 0 +} + +func constraintLessThanEqual(v, c *Version) bool { + return prereleaseCheck(v, c) && v.Compare(c) <= 0 +} + +func constraintPessimistic(v, c *Version) bool { + // Using a pessimistic constraint with a pre-release, restricts versions to pre-releases + if !prereleaseCheck(v, c) || (c.Prerelease() != "" && v.Prerelease() == "") { + return false + } + + // If the version being checked is naturally less than the constraint, then there + // is no way for the version to be valid against the constraint + if v.LessThan(c) { + return false + } + // We'll use this more than once, so grab the length now so it's a little cleaner + // to write the later checks + cs := len(c.segments) + + // If the version being checked has less specificity than the constraint, then there + // is no way for the version to be valid against the constraint + if cs > len(v.segments) { + return false + } + + // Check the segments in the constraint against those in the version. If the version + // being checked, at any point, does not have the same values in each index of the + // constraints segments, then it cannot be valid against the constraint. + for i := 0; i < c.si-1; i++ { + if v.segments[i] != c.segments[i] { + return false + } + } + + // Check the last part of the segment in the constraint. If the version segment at + // this index is less than the constraints segment at this index, then it cannot + // be valid against the constraint + if c.segments[cs-1] > v.segments[cs-1] { + return false + } + + // If nothing has rejected the version by now, it's valid + return true +} diff --git a/vendor/github.com/hashicorp/go-version/go.mod b/vendor/github.com/hashicorp/go-version/go.mod new file mode 100644 index 000000000000..f5285555fa84 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/go-version diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go new file mode 100644 index 000000000000..1032c5606c37 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -0,0 +1,380 @@ +package version + +import ( + "bytes" + "fmt" + "reflect" + "regexp" + "strconv" + "strings" +) + +// The compiled regular expression used to test the validity of a version. +var ( + versionRegexp *regexp.Regexp + semverRegexp *regexp.Regexp +) + +// The raw regular expression string used for testing the validity +// of a version. +const ( + VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + + `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-?([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + + `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + + `?` + + // SemverRegexpRaw requires a separator between version and prerelease + SemverRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + + `(-([0-9]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)|(-([A-Za-z\-~]+[0-9A-Za-z\-~]*(\.[0-9A-Za-z\-~]+)*)))?` + + `(\+([0-9A-Za-z\-~]+(\.[0-9A-Za-z\-~]+)*))?` + + `?` +) + +// Version represents a single version. +type Version struct { + metadata string + pre string + segments []int64 + si int + original string +} + +func init() { + versionRegexp = regexp.MustCompile("^" + VersionRegexpRaw + "$") + semverRegexp = regexp.MustCompile("^" + SemverRegexpRaw + "$") +} + +// NewVersion parses the given version and returns a new +// Version. +func NewVersion(v string) (*Version, error) { + return newVersion(v, versionRegexp) +} + +// NewSemver parses the given version and returns a new +// Version that adheres strictly to SemVer specs +// https://semver.org/ +func NewSemver(v string) (*Version, error) { + return newVersion(v, semverRegexp) +} + +func newVersion(v string, pattern *regexp.Regexp) (*Version, error) { + matches := pattern.FindStringSubmatch(v) + if matches == nil { + return nil, fmt.Errorf("Malformed version: %s", v) + } + segmentsStr := strings.Split(matches[1], ".") + segments := make([]int64, len(segmentsStr)) + si := 0 + for i, str := range segmentsStr { + val, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return nil, fmt.Errorf( + "Error parsing version: %s", err) + } + + segments[i] = int64(val) + si++ + } + + // Even though we could support more than three segments, if we + // got less than three, pad it with 0s. This is to cover the basic + // default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum + for i := len(segments); i < 3; i++ { + segments = append(segments, 0) + } + + pre := matches[7] + if pre == "" { + pre = matches[4] + } + + return &Version{ + metadata: matches[10], + pre: pre, + segments: segments, + si: si, + original: v, + }, nil +} + +// Must is a helper that wraps a call to a function returning (*Version, error) +// and panics if error is non-nil. +func Must(v *Version, err error) *Version { + if err != nil { + panic(err) + } + + return v +} + +// Compare compares this version to another version. This +// returns -1, 0, or 1 if this version is smaller, equal, +// or larger than the other version, respectively. +// +// If you want boolean results, use the LessThan, Equal, +// GreaterThan, GreaterThanOrEqual or LessThanOrEqual methods. +func (v *Version) Compare(other *Version) int { + // A quick, efficient equality check + if v.String() == other.String() { + return 0 + } + + segmentsSelf := v.Segments64() + segmentsOther := other.Segments64() + + // If the segments are the same, we must compare on prerelease info + if reflect.DeepEqual(segmentsSelf, segmentsOther) { + preSelf := v.Prerelease() + preOther := other.Prerelease() + if preSelf == "" && preOther == "" { + return 0 + } + if preSelf == "" { + return 1 + } + if preOther == "" { + return -1 + } + + return comparePrereleases(preSelf, preOther) + } + + // Get the highest specificity (hS), or if they're equal, just use segmentSelf length + lenSelf := len(segmentsSelf) + lenOther := len(segmentsOther) + hS := lenSelf + if lenSelf < lenOther { + hS = lenOther + } + // Compare the segments + // Because a constraint could have more/less specificity than the version it's + // checking, we need to account for a lopsided or jagged comparison + for i := 0; i < hS; i++ { + if i > lenSelf-1 { + // This means Self had the lower specificity + // Check to see if the remaining segments in Other are all zeros + if !allZero(segmentsOther[i:]) { + // if not, it means that Other has to be greater than Self + return -1 + } + break + } else if i > lenOther-1 { + // this means Other had the lower specificity + // Check to see if the remaining segments in Self are all zeros - + if !allZero(segmentsSelf[i:]) { + //if not, it means that Self has to be greater than Other + return 1 + } + break + } + lhs := segmentsSelf[i] + rhs := segmentsOther[i] + if lhs == rhs { + continue + } else if lhs < rhs { + return -1 + } + // Otherwis, rhs was > lhs, they're not equal + return 1 + } + + // if we got this far, they're equal + return 0 +} + +func allZero(segs []int64) bool { + for _, s := range segs { + if s != 0 { + return false + } + } + return true +} + +func comparePart(preSelf string, preOther string) int { + if preSelf == preOther { + return 0 + } + + var selfInt int64 + selfNumeric := true + selfInt, err := strconv.ParseInt(preSelf, 10, 64) + if err != nil { + selfNumeric = false + } + + var otherInt int64 + otherNumeric := true + otherInt, err = strconv.ParseInt(preOther, 10, 64) + if err != nil { + otherNumeric = false + } + + // if a part is empty, we use the other to decide + if preSelf == "" { + if otherNumeric { + return -1 + } + return 1 + } + + if preOther == "" { + if selfNumeric { + return 1 + } + return -1 + } + + if selfNumeric && !otherNumeric { + return -1 + } else if !selfNumeric && otherNumeric { + return 1 + } else if !selfNumeric && !otherNumeric && preSelf > preOther { + return 1 + } else if selfInt > otherInt { + return 1 + } + + return -1 +} + +func comparePrereleases(v string, other string) int { + // the same pre release! + if v == other { + return 0 + } + + // split both pre releases for analyse their parts + selfPreReleaseMeta := strings.Split(v, ".") + otherPreReleaseMeta := strings.Split(other, ".") + + selfPreReleaseLen := len(selfPreReleaseMeta) + otherPreReleaseLen := len(otherPreReleaseMeta) + + biggestLen := otherPreReleaseLen + if selfPreReleaseLen > otherPreReleaseLen { + biggestLen = selfPreReleaseLen + } + + // loop for parts to find the first difference + for i := 0; i < biggestLen; i = i + 1 { + partSelfPre := "" + if i < selfPreReleaseLen { + partSelfPre = selfPreReleaseMeta[i] + } + + partOtherPre := "" + if i < otherPreReleaseLen { + partOtherPre = otherPreReleaseMeta[i] + } + + compare := comparePart(partSelfPre, partOtherPre) + // if parts are equals, continue the loop + if compare != 0 { + return compare + } + } + + return 0 +} + +// Equal tests if two versions are equal. +func (v *Version) Equal(o *Version) bool { + return v.Compare(o) == 0 +} + +// GreaterThan tests if this version is greater than another version. +func (v *Version) GreaterThan(o *Version) bool { + return v.Compare(o) > 0 +} + +// GreaterThanOrEqualTo tests if this version is greater than or equal to another version. +func (v *Version) GreaterThanOrEqual(o *Version) bool { + return v.Compare(o) >= 0 +} + +// LessThan tests if this version is less than another version. +func (v *Version) LessThan(o *Version) bool { + return v.Compare(o) < 0 +} + +// LessThanOrEqualTo tests if this version is less than or equal to another version. +func (v *Version) LessThanOrEqual(o *Version) bool { + return v.Compare(o) <= 0 +} + +// Metadata returns any metadata that was part of the version +// string. +// +// Metadata is anything that comes after the "+" in the version. +// For example, with "1.2.3+beta", the metadata is "beta". +func (v *Version) Metadata() string { + return v.metadata +} + +// Prerelease returns any prerelease data that is part of the version, +// or blank if there is no prerelease data. +// +// Prerelease information is anything that comes after the "-" in the +// version (but before any metadata). For example, with "1.2.3-beta", +// the prerelease information is "beta". +func (v *Version) Prerelease() string { + return v.pre +} + +// Segments returns the numeric segments of the version as a slice of ints. +// +// This excludes any metadata or pre-release information. For example, +// for a version "1.2.3-beta", segments will return a slice of +// 1, 2, 3. +func (v *Version) Segments() []int { + segmentSlice := make([]int, len(v.segments)) + for i, v := range v.segments { + segmentSlice[i] = int(v) + } + return segmentSlice +} + +// Segments64 returns the numeric segments of the version as a slice of int64s. +// +// This excludes any metadata or pre-release information. For example, +// for a version "1.2.3-beta", segments will return a slice of +// 1, 2, 3. +func (v *Version) Segments64() []int64 { + result := make([]int64, len(v.segments)) + copy(result, v.segments) + return result +} + +// String returns the full version string included pre-release +// and metadata information. +// +// This value is rebuilt according to the parsed segments and other +// information. Therefore, ambiguities in the version string such as +// prefixed zeroes (1.04.0 => 1.4.0), `v` prefix (v1.0.0 => 1.0.0), and +// missing parts (1.0 => 1.0.0) will be made into a canonicalized form +// as shown in the parenthesized examples. +func (v *Version) String() string { + var buf bytes.Buffer + fmtParts := make([]string, len(v.segments)) + for i, s := range v.segments { + // We can ignore err here since we've pre-parsed the values in segments + str := strconv.FormatInt(s, 10) + fmtParts[i] = str + } + fmt.Fprintf(&buf, strings.Join(fmtParts, ".")) + if v.pre != "" { + fmt.Fprintf(&buf, "-%s", v.pre) + } + if v.metadata != "" { + fmt.Fprintf(&buf, "+%s", v.metadata) + } + + return buf.String() +} + +// Original returns the original parsed version as-is, including any +// potential whitespace, `v` prefix, etc. +func (v *Version) Original() string { + return v.original +} diff --git a/vendor/github.com/hashicorp/go-version/version_collection.go b/vendor/github.com/hashicorp/go-version/version_collection.go new file mode 100644 index 000000000000..cc888d43e6b6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-version/version_collection.go @@ -0,0 +1,17 @@ +package version + +// Collection is a type that implements the sort.Interface interface +// so that versions can be sorted. +type Collection []*Version + +func (v Collection) Len() int { + return len(v) +} + +func (v Collection) Less(i, j int) bool { + return v[i].LessThan(v[j]) +} + +func (v Collection) Swap(i, j int) { + v[i], v[j] = v[j], v[i] +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 8360fc5aeb8e..f76027d7138b 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -5,6 +5,9 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks +# code.gitea.io/sdk/gitea v0.12.1 +## explicit +code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0 ## explicit gitea.com/lunny/levelqueue @@ -427,6 +430,8 @@ github.com/hashicorp/go-cleanhttp # github.com/hashicorp/go-retryablehttp v0.6.6 ## explicit github.com/hashicorp/go-retryablehttp +# github.com/hashicorp/go-version v1.2.0 +github.com/hashicorp/go-version # github.com/hashicorp/hcl v1.0.0 github.com/hashicorp/hcl github.com/hashicorp/hcl/hcl/ast From 6e20e94821844c098cb9f1e77d204d9964a5c89a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 03:22:07 +0200 Subject: [PATCH 02/46] update gitea sdk to 9e280adb4da --- go.mod | 3 +- go.sum | 6 +- vendor/code.gitea.io/sdk/gitea/admin_user.go | 14 ++ vendor/code.gitea.io/sdk/gitea/client.go | 2 +- vendor/code.gitea.io/sdk/gitea/hook.go | 11 ++ vendor/code.gitea.io/sdk/gitea/issue.go | 23 +++ .../code.gitea.io/sdk/gitea/issue_comment.go | 22 +++ vendor/code.gitea.io/sdk/gitea/issue_label.go | 44 ++++- .../sdk/gitea/issue_milestone.go | 27 +++- .../sdk/gitea/issue_tracked_time.go | 13 +- .../code.gitea.io/sdk/gitea/notifications.go | 63 +++++++- vendor/code.gitea.io/sdk/gitea/org.go | 72 +++++++-- vendor/code.gitea.io/sdk/gitea/org_type.go | 27 ---- vendor/code.gitea.io/sdk/gitea/pull.go | 32 +++- vendor/code.gitea.io/sdk/gitea/pull_review.go | 44 ++++- vendor/code.gitea.io/sdk/gitea/release.go | 16 +- vendor/code.gitea.io/sdk/gitea/repo.go | 150 ++++++++++++++---- .../sdk/gitea/repo_branch_protection.go | 46 +++--- .../sdk/gitea/repo_collaborator.go | 12 ++ vendor/code.gitea.io/sdk/gitea/settings.go | 34 ++++ .../hashicorp/go-version/.travis.yml | 13 -- .../github.com/hashicorp/go-version/README.md | 3 +- .../hashicorp/go-version/version.go | 8 +- vendor/modules.txt | 5 +- 24 files changed, 553 insertions(+), 137 deletions(-) delete mode 100644 vendor/code.gitea.io/sdk/gitea/org_type.go create mode 100644 vendor/code.gitea.io/sdk/gitea/settings.go delete mode 100644 vendor/github.com/hashicorp/go-version/.travis.yml diff --git a/go.mod b/go.mod index fd389e8bb5b9..fd03a16b46a2 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.14 require ( cloud.google.com/go v0.45.0 // indirect code.gitea.io/gitea-vet v0.2.1 - code.gitea.io/sdk/gitea v0.12.1 + code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 @@ -55,6 +55,7 @@ require ( github.com/google/uuid v1.1.1 github.com/gorilla/context v1.1.1 github.com/hashicorp/go-retryablehttp v0.6.6 // indirect + github.com/hashicorp/go-version v1.2.1 // indirect github.com/huandu/xstrings v1.3.0 github.com/issue9/assert v1.3.2 // indirect github.com/issue9/identicon v1.0.1 diff --git a/go.sum b/go.sum index 4d7cff88eb8a..fb565730e66e 100644 --- a/go.sum +++ b/go.sum @@ -11,8 +11,8 @@ cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbf cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/sdk/gitea v0.12.1 h1:bMgjEqPnNX/i6TpVwXwpjJtFOnUSuC9P6yy/jjy8sjY= -code.gitea.io/sdk/gitea v0.12.1/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= +code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa h1:DkcOvLx4GFIOgzOl6wKcocK3JIl0a9aV4u/MXUVS3SA= +code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b h1:vXt85uYV17KURaUlhU7v4GbCShkqRZDSfo0TkC0YCjQ= @@ -404,6 +404,8 @@ github.com/hashicorp/go-retryablehttp v0.6.6 h1:HJunrbHTDDbBb/ay4kxa1n+dLmttUlnP github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.2.1 h1:zEfKbn2+PDgroKdiOzqiE8rsmLqU2uwi5PB5pBJ3TkI= +github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= diff --git a/vendor/code.gitea.io/sdk/gitea/admin_user.go b/vendor/code.gitea.io/sdk/gitea/admin_user.go index c447934395b0..13a877653e2a 100644 --- a/vendor/code.gitea.io/sdk/gitea/admin_user.go +++ b/vendor/code.gitea.io/sdk/gitea/admin_user.go @@ -35,8 +35,22 @@ type CreateUserOption struct { SendNotify bool `json:"send_notify"` } +// Validate the CreateUserOption struct +func (opt CreateUserOption) Validate() error { + if len(opt.Email) == 0 { + return fmt.Errorf("email is empty") + } + if len(opt.Username) == 0 { + return fmt.Errorf("username is empty") + } + return nil +} + // AdminCreateUser create a user func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go index 04f6a4cf2436..ccbe10e9a9aa 100644 --- a/vendor/code.gitea.io/sdk/gitea/client.go +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -22,7 +22,7 @@ var jsonHeader = http.Header{"content-type": []string{"application/json"}} // Version return the library version func Version() string { - return "0.12.0" + return "0.13.0" } // Client represents a Gitea API client. diff --git a/vendor/code.gitea.io/sdk/gitea/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go index f89a6e952aa7..1ca1a3b0eb7a 100644 --- a/vendor/code.gitea.io/sdk/gitea/hook.go +++ b/vendor/code.gitea.io/sdk/gitea/hook.go @@ -64,8 +64,19 @@ type CreateHookOption struct { Active bool `json:"active"` } +// Validate the CreateHookOption struct +func (opt CreateHookOption) Validate() error { + if len(opt.Type) == 0 { + return fmt.Errorf("hook type needed") + } + return nil +} + // CreateOrgHook create one hook for an organization, with options func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/issue.go b/vendor/code.gitea.io/sdk/gitea/issue.go index 0e57147f180e..dd591f3c1e76 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue.go +++ b/vendor/code.gitea.io/sdk/gitea/issue.go @@ -44,6 +44,7 @@ type Issue struct { Assignees []*User `json:"assignees"` // Whether the issue is open or closed State StateType `json:"state"` + IsLocked bool `json:"is_locked"` Comments int `json:"comments"` Created time.Time `json:"created_at"` Updated time.Time `json:"updated_at"` @@ -173,8 +174,19 @@ type CreateIssueOption struct { Closed bool `json:"closed"` } +// Validate the CreateIssueOption struct +func (opt CreateIssueOption) Validate() error { + if len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + return nil +} + // CreateIssue create a new issue for a given repository func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -195,8 +207,19 @@ type EditIssueOption struct { Deadline *time.Time `json:"due_date"` } +// Validate the EditIssueOption struct +func (opt EditIssueOption) Validate() error { + if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + return nil +} + // EditIssue modify an existing issue for a given repository func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/issue_comment.go b/vendor/code.gitea.io/sdk/gitea/issue_comment.go index cc8cf9fbdbab..1c0a1de4fc1a 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_comment.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_comment.go @@ -77,8 +77,19 @@ type CreateIssueCommentOption struct { Body string `json:"body"` } +// Validate the CreateIssueCommentOption struct +func (opt CreateIssueCommentOption) Validate() error { + if len(opt.Body) == 0 { + return fmt.Errorf("body is empty") + } + return nil +} + // CreateIssueComment create comment on an issue. func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -92,8 +103,19 @@ type EditIssueCommentOption struct { Body string `json:"body"` } +// Validate the EditIssueCommentOption struct +func (opt EditIssueCommentOption) Validate() error { + if len(opt.Body) == 0 { + return fmt.Errorf("body is empty") + } + return nil +} + // EditIssueComment edits an issue comment. func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/issue_label.go b/vendor/code.gitea.io/sdk/gitea/issue_label.go index c5e560ab07d5..d067d70a5f93 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_label.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_label.go @@ -8,6 +8,8 @@ import ( "bytes" "encoding/json" "fmt" + "regexp" + "strings" ) // Label a label to an issue or a pr @@ -33,7 +35,6 @@ func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*L } // GetRepoLabel get one label of repository by repo it -// TODO: maybe we need get a label by name func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, error) { label := new(Label) return label, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label) @@ -47,8 +48,26 @@ type CreateLabelOption struct { Description string `json:"description"` } +// Validate the CreateLabelOption struct +func (opt CreateLabelOption) Validate() error { + aw, err := regexp.MatchString("^#?[0-9,a-f,A-F]{6}$", opt.Color) + if err != nil { + return err + } + if !aw { + return fmt.Errorf("invalid color format") + } + if len(strings.TrimSpace(opt.Name)) == 0 { + return fmt.Errorf("empty name not allowed") + } + return nil +} + // CreateLabel create one label of repository func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { + if err := opt.Validate(); err != nil { + return nil, err + } if len(opt.Color) == 6 { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { opt.Color = "#" + opt.Color @@ -70,8 +89,30 @@ type EditLabelOption struct { Description *string `json:"description"` } +// Validate the EditLabelOption struct +func (opt EditLabelOption) Validate() error { + if opt.Color != nil { + aw, err := regexp.MatchString("^#?[0-9,a-f,A-F]{6}$", *opt.Color) + if err != nil { + return err + } + if !aw { + return fmt.Errorf("invalid color format") + } + } + if opt.Name != nil { + if len(strings.TrimSpace(*opt.Name)) == 0 { + return fmt.Errorf("empty name not allowed") + } + } + return nil +} + // EditLabel modify one label with options func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -81,7 +122,6 @@ func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (* } // DeleteLabel delete one label of repository by id -// TODO: maybe we need delete by name func (c *Client) DeleteLabel(owner, repo string, id int64) error { _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil) return err diff --git a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go index 41fca1fd5e75..1270925c913c 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "net/url" + "strings" "time" ) @@ -64,8 +65,19 @@ type CreateMilestoneOption struct { Deadline *time.Time `json:"due_on"` } +// Validate the CreateMilestoneOption struct +func (opt CreateMilestoneOption) Validate() error { + if len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + return nil +} + // CreateMilestone create one milestone with options func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -76,7 +88,7 @@ func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) // make creating closed milestones need gitea >= v1.13.0 // this make it backwards compatible if err == nil && opt.State == StateClosed && milestone.State != StateClosed { - closed := "closed" + closed := StateClosed return c.EditMilestone(owner, repo, milestone.ID, EditMilestoneOption{ State: &closed, }) @@ -89,12 +101,23 @@ func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) type EditMilestoneOption struct { Title string `json:"title"` Description *string `json:"description"` - State *string `json:"state"` + State *StateType `json:"state"` Deadline *time.Time `json:"due_on"` } +// Validate the EditMilestoneOption struct +func (opt EditMilestoneOption) Validate() error { + if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + return nil +} + // EditMilestone modify milestone with options func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go index 51f1a99b66b6..d4b6af62ba11 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go @@ -46,15 +46,26 @@ func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, error) { // AddTimeOption options for adding time to an issue type AddTimeOption struct { // time in seconds - Time int64 `json:"time" binding:"Required"` + Time int64 `json:"time"` // optional Created time.Time `json:"created"` // optional User string `json:"user_name"` } +// Validate the AddTimeOption struct +func (opt AddTimeOption) Validate() error { + if opt.Time == 0 { + return fmt.Errorf("no time to add") + } + return nil +} + // AddTime adds time to issue with the given index func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/notifications.go b/vendor/code.gitea.io/sdk/gitea/notifications.go index 188de88c39b7..c966b7e3a038 100644 --- a/vendor/code.gitea.io/sdk/gitea/notifications.go +++ b/vendor/code.gitea.io/sdk/gitea/notifications.go @@ -29,16 +29,31 @@ type NotificationSubject struct { Type string `json:"type" binding:"In(Issue,Pull,Commit)"` } +// NotifyStatus notification status type +type NotifyStatus string + +const ( + // NotifyStatusUnread was not read + NotifyStatusUnread NotifyStatus = "unread" + // NotifyStatusRead was already read by user + NotifyStatusRead NotifyStatus = "read" + // NotifyStatusPinned notification is pinned by user + NotifyStatusPinned NotifyStatus = "pinned" +) + // ListNotificationOptions represents the filter options type ListNotificationOptions struct { ListOptions Since time.Time Before time.Time + Status []NotifyStatus } -// MarkNotificationOptions represents the filter options +// MarkNotificationOptions represents the filter & modify options type MarkNotificationOptions struct { LastReadAt time.Time + Status []NotifyStatus + ToStatus NotifyStatus } // QueryEncode encode options to url query @@ -50,18 +65,43 @@ func (opt *ListNotificationOptions) QueryEncode() string { if !opt.Before.IsZero() { query.Add("before", opt.Before.Format(time.RFC3339)) } + for _, s := range opt.Status { + query.Add("status-types", string(s)) + } return query.Encode() } +// Validate the CreateUserOption struct +func (opt ListNotificationOptions) Validate(c *Client) error { + if len(opt.Status) != 0 { + return c.CheckServerVersionConstraint(">=1.12.3") + } + return nil +} + // QueryEncode encode options to url query func (opt *MarkNotificationOptions) QueryEncode() string { query := make(url.Values) if !opt.LastReadAt.IsZero() { query.Add("last_read_at", opt.LastReadAt.Format(time.RFC3339)) } + for _, s := range opt.Status { + query.Add("status-types", string(s)) + } + if len(opt.ToStatus) != 0 { + query.Add("to-status", string(opt.ToStatus)) + } return query.Encode() } +// Validate the CreateUserOption struct +func (opt MarkNotificationOptions) Validate(c *Client) error { + if len(opt.Status) != 0 || len(opt.ToStatus) != 0 { + return c.CheckServerVersionConstraint(">=1.12.3") + } + return nil +} + // CheckNotifications list users's notification threads func (c *Client) CheckNotifications() (int64, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { @@ -84,16 +124,24 @@ func (c *Client) GetNotification(id int64) (*NotificationThread, error) { } // ReadNotification mark notification thread as read by ID -func (c *Client) ReadNotification(id int64) error { +// It optionally takes a second argument if status has to be set other than 'read' +func (c *Client) ReadNotification(id int64, status ...NotifyStatus) error { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return err } - _, err := c.getResponse("PATCH", fmt.Sprintf("/notifications/threads/%d", id), nil, nil) + link := fmt.Sprintf("/notifications/threads/%d", id) + if len(status) != 0 { + link += fmt.Sprintf("?to-status=%s", status[0]) + } + _, err := c.getResponse("PATCH", link, nil, nil) return err } // ListNotifications list users's notification threads func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, error) { + if err := opt.Validate(c); err != nil { + return nil, err + } if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return nil, err } @@ -105,6 +153,9 @@ func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*Notification // ReadNotifications mark notification threads as read func (c *Client) ReadNotifications(opt MarkNotificationOptions) error { + if err := opt.Validate(c); err != nil { + return err + } if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return err } @@ -116,6 +167,9 @@ func (c *Client) ReadNotifications(opt MarkNotificationOptions) error { // ListRepoNotifications list users's notification threads on a specific repo func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, error) { + if err := opt.Validate(c); err != nil { + return nil, err + } if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return nil, err } @@ -127,6 +181,9 @@ func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificat // ReadRepoNotifications mark notification threads as read on a specific repo func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) error { + if err := opt.Validate(c); err != nil { + return err + } if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return err } diff --git a/vendor/code.gitea.io/sdk/gitea/org.go b/vendor/code.gitea.io/sdk/gitea/org.go index 61ade3095c2c..750953e45898 100644 --- a/vendor/code.gitea.io/sdk/gitea/org.go +++ b/vendor/code.gitea.io/sdk/gitea/org.go @@ -23,6 +23,20 @@ type Organization struct { Visibility string `json:"visibility"` } +// VisibleType defines the visibility +type VisibleType string + +const ( + // VisibleTypePublic Visible for everyone + VisibleTypePublic VisibleType = "public" + + // VisibleTypeLimited Visible for every connected user + VisibleTypeLimited VisibleType = "limited" + + // VisibleTypePrivate Visible only for organization's members + VisibleTypePrivate VisibleType = "private" +) + // ListOrgsOptions options for listing organizations type ListOrgsOptions struct { ListOptions @@ -50,18 +64,35 @@ func (c *Client) GetOrg(orgname string) (*Organization, error) { // CreateOrgOption options for creating an organization type CreateOrgOption struct { - UserName string `json:"username"` - FullName string `json:"full_name"` - Description string `json:"description"` - Website string `json:"website"` - Location string `json:"location"` - // possible values are `public` (default), `limited` or `private` - // enum: public,limited,private - Visibility string `json:"visibility"` + Name string `json:"username"` + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` + Visibility VisibleType `json:"visibility"` +} + +// checkVisibilityOpt check if mode exist +func checkVisibilityOpt(v VisibleType) bool { + return v == VisibleTypePublic || v == VisibleTypeLimited || v == VisibleTypePrivate +} + +// Validate the CreateOrgOption struct +func (opt CreateOrgOption) Validate() error { + if len(opt.Name) == 0 { + return fmt.Errorf("empty org name") + } + if len(opt.Visibility) != 0 && !checkVisibilityOpt(opt.Visibility) { + return fmt.Errorf("infalid bisibility option") + } + return nil } // CreateOrg creates an organization func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -72,17 +103,26 @@ func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, error) { // EditOrgOption options for editing an organization type EditOrgOption struct { - FullName string `json:"full_name"` - Description string `json:"description"` - Website string `json:"website"` - Location string `json:"location"` - // possible values are `public`, `limited` or `private` - // enum: public,limited,private - Visibility string `json:"visibility"` + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` + Visibility VisibleType `json:"visibility"` +} + +// Validate the EditOrgOption struct +func (opt EditOrgOption) Validate() error { + if len(opt.Visibility) != 0 && !checkVisibilityOpt(opt.Visibility) { + return fmt.Errorf("infalid bisibility option") + } + return nil } // EditOrg modify one organization via options func (c *Client) EditOrg(orgname string, opt EditOrgOption) error { + if err := opt.Validate(); err != nil { + return err + } body, err := json.Marshal(&opt) if err != nil { return err @@ -93,6 +133,6 @@ func (c *Client) EditOrg(orgname string, opt EditOrgOption) error { // DeleteOrg deletes an organization func (c *Client) DeleteOrg(orgname string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), nil, nil) + _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, nil) return err } diff --git a/vendor/code.gitea.io/sdk/gitea/org_type.go b/vendor/code.gitea.io/sdk/gitea/org_type.go deleted file mode 100644 index 930be186a373..000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org_type.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2019 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package gitea - -// VisibleType defines the visibility (Organization only) -type VisibleType int - -const ( - // VisibleTypePublic Visible for everyone - VisibleTypePublic VisibleType = iota - - // VisibleTypeLimited Visible for every connected user - VisibleTypeLimited - - // VisibleTypePrivate Visible only for organization's members - VisibleTypePrivate -) - -// ExtractKeysFromMapString provides a slice of keys from map -func ExtractKeysFromMapString(in map[string]VisibleType) (keys []string) { - for k := range in { - keys = append(keys, k) - } - return -} diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go index 5005b18e587f..d1659dc4c2c4 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull.go +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -10,6 +10,7 @@ import ( "encoding/json" "fmt" "net/url" + "strings" "time" ) @@ -35,6 +36,7 @@ type PullRequest struct { Assignee *User `json:"assignee"` Assignees []*User `json:"assignees"` State StateType `json:"state"` + IsLocked bool `json:"is_locked"` Comments int `json:"comments"` HTMLURL string `json:"html_url"` @@ -148,8 +150,24 @@ type EditPullRequestOption struct { Deadline *time.Time `json:"due_date"` } +// Validate the EditPullRequestOption struct +func (opt EditPullRequestOption) Validate(c *Client) error { + if len(opt.Title) != 0 && len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + if len(opt.Base) != 0 { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return fmt.Errorf("can not change base gitea to old") + } + } + return nil +} + // EditPullRequest modify pull request with PR id and options func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, error) { + if err := opt.Validate(c); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -166,13 +184,21 @@ type MergePullRequestOption struct { 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) { +// Validate the MergePullRequestOption struct +func (opt MergePullRequestOption) Validate(c *Client) error { if opt.Style == MergeStyleSquash { if err := c.CheckServerVersionConstraint(">=1.11.5"); err != nil { - return false, err + return err } } + return nil +} + +// MergePullRequest merge a PR to repository by PR id +func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, error) { + if err := opt.Validate(c); err != nil { + return false, err + } body, err := json.Marshal(&opt) if err != nil { return false, err diff --git a/vendor/code.gitea.io/sdk/gitea/pull_review.go b/vendor/code.gitea.io/sdk/gitea/pull_review.go index 9ff708a12cf3..8e5a5e84601a 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull_review.go +++ b/vendor/code.gitea.io/sdk/gitea/pull_review.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "net/url" + "strings" "time" ) @@ -40,8 +41,7 @@ type PullReview struct { Stale bool `json:"stale"` Official bool `json:"official"` CodeCommentsCount int `json:"comments_count"` - // swagger:strfmt date-time - Submitted time.Time `json:"submitted_at"` + Submitted time.Time `json:"submitted_at"` HTMLURL string `json:"html_url"` HTMLPullURL string `json:"pull_request_url"` @@ -54,9 +54,7 @@ type PullReviewComment struct { 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"` @@ -100,6 +98,38 @@ type ListPullReviewsOptions struct { ListOptions } +// Validate the CreatePullReviewOptions struct +func (opt CreatePullReviewOptions) Validate() error { + if opt.State != ReviewStateApproved && len(strings.TrimSpace(opt.Body)) == 0 { + return fmt.Errorf("body is empty") + } + for i := range opt.Comments { + if err := opt.Comments[i].Validate(); err != nil { + return err + } + } + return nil +} + +// Validate the SubmitPullReviewOptions struct +func (opt SubmitPullReviewOptions) Validate() error { + if opt.State != ReviewStateApproved && len(strings.TrimSpace(opt.Body)) == 0 { + return fmt.Errorf("body is empty") + } + return nil +} + +// Validate the CreatePullReviewComment struct +func (opt CreatePullReviewComment) Validate() error { + if len(strings.TrimSpace(opt.Body)) == 0 { + return fmt.Errorf("body is empty") + } + if opt.NewLineNum != 0 && opt.OldLineNum != 0 { + return fmt.Errorf("old and new line num are set, cant identify the code comment position") + } + return nil +} + // ListPullReviews lists all reviews of a pull request func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { @@ -158,6 +188,9 @@ func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePul if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return nil, err } + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -173,6 +206,9 @@ func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt Submi if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return nil, err } + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/release.go b/vendor/code.gitea.io/sdk/gitea/release.go index fe5c023de031..44cdc00d2099 100644 --- a/vendor/code.gitea.io/sdk/gitea/release.go +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/json" "fmt" + "strings" "time" ) @@ -63,9 +64,20 @@ type CreateReleaseOption struct { IsPrerelease bool `json:"prerelease"` } +// Validate the CreateReleaseOption struct +func (opt CreateReleaseOption) Validate() error { + if len(strings.TrimSpace(opt.Title)) == 0 { + return fmt.Errorf("title is empty") + } + return nil +} + // CreateRelease create a release -func (c *Client) CreateRelease(user, repo string, form CreateReleaseOption) (*Release, error) { - body, err := json.Marshal(form) +func (c *Client) CreateRelease(user, repo string, opt CreateReleaseOption) (*Release, error) { + if err := opt.Validate(); err != nil { + return nil, err + } + body, err := json.Marshal(opt) if err != nil { return nil, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo.go b/vendor/code.gitea.io/sdk/gitea/repo.go index 80f24b889997..0acc6ee34f01 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo.go +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "net/url" + "strings" "time" ) @@ -57,6 +58,20 @@ type Repository struct { AvatarURL string `json:"avatar_url"` } +// RepoType represent repo type +type RepoType string + +const ( + // RepoTypeNone dont specify a type + RepoTypeNone RepoType = "" + // RepoTypeSource is the default repo type + RepoTypeSource RepoType = "source" + // RepoTypeFork is a repo witch was forked from an other one + RepoTypeFork RepoType = "fork" + // RepoTypeMirror represents an mirror repo + RepoTypeMirror RepoType = "mirror" +) + // ListReposOptions options for listing repositories type ListReposOptions struct { ListOptions @@ -91,17 +106,52 @@ func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repositor // 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 + + // The keyword to query + Keyword string + // Limit search to repositories with keyword as topic + KeywordIsTopic bool + // Include search of keyword within repository description + KeywordInDescription bool + + /* + User Filter + */ + + // Repo Owner + OwnerID int64 + // Stared By UserID + StarredByUserID int64 + + /* + Repo Attributes + */ + + // pubic, private or all repositories (defaults to all) + IsPrivate *bool + // archived, non-archived or all repositories (defaults to all) + IsArchived *bool + // Exclude template repos from search + ExcludeTemplate bool + // Filter by "fork", "source", "mirror" + Type RepoType + + /* + Sort Filters + */ + + // sort repos by attribute. Supported values are "alpha", "created", "updated", "size", and "id". Default is "alpha" + Sort string + // sort order, either "asc" (ascending) or "desc" (descending). Default is "asc", ignored if "sort" is not specified. + Order string + // Repo owner to prioritize in the results + PrioritizedByOwnerID int64 + + /* + Cover EdgeCases + */ + // if set all other options are ignored and this string is used as query + RawQuery string } // QueryEncode turns options into querystring argument @@ -110,34 +160,46 @@ func (opt *SearchRepoOptions) QueryEncode() string { 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.KeywordIsTopic { + query.Add("topic", "true") } - - if opt.PriorityOwnerID > 0 { - query.Add("priority_owner_id", fmt.Sprintf("%d", opt.PriorityOwnerID)) + if opt.KeywordInDescription { + query.Add("includeDesc", "true") } - if opt.StarredBy > 0 { - query.Add("starredBy", fmt.Sprintf("%d", opt.StarredBy)) + // User Filter + if opt.OwnerID > 0 { + query.Add("uid", fmt.Sprintf("%d", opt.OwnerID)) + query.Add("exclusive", "true") } - - query.Add("private", fmt.Sprintf("%t", opt.Private)) - query.Add("template", fmt.Sprintf("%t", opt.Template)) - - if opt.Mode != "" { - query.Add("mode", opt.Mode) + if opt.StarredByUserID > 0 { + query.Add("starredBy", fmt.Sprintf("%d", opt.StarredByUserID)) } - query.Add("exclusive", fmt.Sprintf("%t", opt.Exclusive)) + // Repo Attributes + if opt.IsPrivate != nil { + query.Add("is_private", fmt.Sprintf("%v", opt.IsPrivate)) + } + if opt.IsArchived != nil { + query.Add("archived", fmt.Sprintf("%v", opt.IsArchived)) + } + if opt.ExcludeTemplate { + query.Add("template", "false") + } + if len(opt.Type) != 0 { + query.Add("mode", string(opt.Type)) + } + // Sort Filters if opt.Sort != "" { query.Add("sort", opt.Sort) } + if opt.PrioritizedByOwnerID > 0 { + query.Add("priority_owner_id", fmt.Sprintf("%d", opt.PrioritizedByOwnerID)) + } + if opt.Order != "" { + query.Add("order", opt.Order) + } return query.Encode() } @@ -152,7 +214,20 @@ func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) { resp := new(searchRepoResponse) link, _ := url.Parse("/repos/search") - link.RawQuery = opt.QueryEncode() + + if len(opt.RawQuery) != 0 { + link.RawQuery = opt.RawQuery + } else { + link.RawQuery = opt.QueryEncode() + // IsPrivate only works on gitea >= 1.12.0 + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil && opt.IsPrivate != nil { + if *opt.IsPrivate { + // private repos only not supported on gitea <= 1.11.x + return nil, err + } + link.Query().Add("private", "false") + } + } err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) return resp.Repos, err @@ -161,7 +236,6 @@ func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) { // CreateRepoOption options when creating repository type CreateRepoOption struct { // Name of the repository to create - // Name string `json:"name"` // Description of the repository to create Description string `json:"description"` @@ -181,8 +255,19 @@ type CreateRepoOption struct { DefaultBranch string `json:"default_branch"` } +// Validate the CreateRepoOption struct +func (opt CreateRepoOption) Validate() error { + if len(strings.TrimSpace(opt.Name)) == 0 { + return fmt.Errorf("name is empty") + } + return nil +} + // CreateRepo creates a repository for authenticated user. func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -193,6 +278,9 @@ func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) { // CreateOrgRepo creates an organization repository for authenticated user. func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go index b7ef96c74267..31bba9c772d7 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go @@ -14,30 +14,28 @@ import ( // 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"` + 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"` + Created time.Time `json:"created_at"` + Updated time.Time `json:"updated_at"` } // CreateBranchProtectionOption options for creating a branch protection diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go index e13ccdbd3876..dbb72b268012 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -41,8 +41,20 @@ type AddCollaboratorOption struct { Permission *string `json:"permission"` } +// Validate the AddCollaboratorOption struct +func (opt AddCollaboratorOption) Validate() error { + if opt.Permission != nil && + *opt.Permission != "read" && *opt.Permission != "write" && *opt.Permission != "admin" { + return fmt.Errorf("permission mode invalid") + } + return nil +} + // AddCollaborator add some user as a collaborator of a repository func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) error { + if err := opt.Validate(); err != nil { + return err + } body, err := json.Marshal(&opt) if err != nil { return err diff --git a/vendor/code.gitea.io/sdk/gitea/settings.go b/vendor/code.gitea.io/sdk/gitea/settings.go new file mode 100644 index 000000000000..42d2bd91e673 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/settings.go @@ -0,0 +1,34 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +// GlobalUISettings represent the global ui settings of a gitea instance witch is exposed by API +type GlobalUISettings struct { + AllowedReactions []string `json:"allowed_reactions"` +} + +// GlobalRepoSettings represent the global repository settings of a gitea instance witch is exposed by API +type GlobalRepoSettings struct { + MirrorsDisabled bool `json:"mirrors_disabled"` + HTTPGitDisabled bool `json:"http_git_disabled"` +} + +// GetGlobalUISettings get global ui settings witch are exposed by API +func (c *Client) GetGlobalUISettings() (settings *GlobalUISettings, err error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + conf := new(GlobalUISettings) + return conf, c.getParsedResponse("GET", "/settings/ui", jsonHeader, nil, &conf) +} + +// GetGlobalRepoSettings get global repository settings witch are exposed by API +func (c *Client) GetGlobalRepoSettings() (settings *GlobalRepoSettings, err error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + conf := new(GlobalRepoSettings) + return conf, c.getParsedResponse("GET", "/settings/repository", jsonHeader, nil, &conf) +} diff --git a/vendor/github.com/hashicorp/go-version/.travis.yml b/vendor/github.com/hashicorp/go-version/.travis.yml deleted file mode 100644 index 01c5dc219afa..000000000000 --- a/vendor/github.com/hashicorp/go-version/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.2 - - 1.3 - - 1.4 - - 1.9 - - "1.10" - - 1.11 - - 1.12 - -script: - - go test diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md index 6f3a15ce7721..851a337beb41 100644 --- a/vendor/github.com/hashicorp/go-version/README.md +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,6 @@ # Versioning Library for Go -[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version) +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/master) +[![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go index 1032c5606c37..09703e8e6ff0 100644 --- a/vendor/github.com/hashicorp/go-version/version.go +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -280,6 +280,10 @@ func comparePrereleases(v string, other string) int { // Equal tests if two versions are equal. func (v *Version) Equal(o *Version) bool { + if v == nil || o == nil { + return v == o + } + return v.Compare(o) == 0 } @@ -288,7 +292,7 @@ func (v *Version) GreaterThan(o *Version) bool { return v.Compare(o) > 0 } -// GreaterThanOrEqualTo tests if this version is greater than or equal to another version. +// GreaterThanOrEqual tests if this version is greater than or equal to another version. func (v *Version) GreaterThanOrEqual(o *Version) bool { return v.Compare(o) >= 0 } @@ -298,7 +302,7 @@ func (v *Version) LessThan(o *Version) bool { return v.Compare(o) < 0 } -// LessThanOrEqualTo tests if this version is less than or equal to another version. +// LessThanOrEqual tests if this version is less than or equal to another version. func (v *Version) LessThanOrEqual(o *Version) bool { return v.Compare(o) <= 0 } diff --git a/vendor/modules.txt b/vendor/modules.txt index f76027d7138b..1976247f36f2 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -5,7 +5,7 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks -# code.gitea.io/sdk/gitea v0.12.1 +# code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa ## explicit code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0 @@ -430,7 +430,8 @@ github.com/hashicorp/go-cleanhttp # github.com/hashicorp/go-retryablehttp v0.6.6 ## explicit github.com/hashicorp/go-retryablehttp -# github.com/hashicorp/go-version v1.2.0 +# github.com/hashicorp/go-version v1.2.1 +## explicit github.com/hashicorp/go-version # github.com/hashicorp/hcl v1.0.0 github.com/hashicorp/hcl From 08e5cb2c8d1b895684e1d17f8a089b38c865f123 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 03:24:50 +0200 Subject: [PATCH 03/46] adapt feat of updated sdk --- modules/migrations/gitea_downloader.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 7a058c38bb09..823862827df2 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -343,7 +343,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err Closed: issue.Closed, Reactions: reactions, Labels: labels, - // IsLocked: issue.IsLocked, // ToDo on sdk release v0.13.0 + IsLocked: issue.IsLocked, }) } @@ -484,8 +484,8 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques Merged: pr.HasMerged, MergedTime: pr.Merged, MergeCommitSHA: mergeCommitSHA, - // IsLocked: pr.IsLocked, sdk v0.13.0 TODO - PatchURL: pr.PatchURL, + IsLocked: pr.IsLocked, + PatchURL: pr.PatchURL, Head: base.PullRequestBranch{ Ref: headRef, SHA: headSHA, From 70bcc3991c57d8d9f9795fa72d5babe88732cf25 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 04:30:37 +0200 Subject: [PATCH 04/46] releases now works --- modules/migrations/gitea_downloader.go | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 823862827df2..362de28957d0 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -146,9 +146,8 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { } for i := range ms { - var state = "open" - // ToDo: expose this info + // https://github.com/go-gitea/gitea/issues/12655 createdAT := time.Now() var updatedAT *time.Time if ms[i].Closed != nil { @@ -163,7 +162,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { Created: createdAT, Updated: updatedAT, Closed: ms[i].Closed, - State: state, + State: string(ms[i].State), }) } if len(ms) < perPage { @@ -207,16 +206,17 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { func (g *GiteaDownloader) convertGiteaRelease(rel *gitea.Release) *base.Release { r := &base.Release{ - TagName: rel.TagName, - Name: rel.Title, - Body: rel.Note, - Draft: rel.IsDraft, - Prerelease: rel.IsPrerelease, - PublisherID: rel.Publisher.ID, - PublisherName: rel.Publisher.UserName, - PublisherEmail: rel.Publisher.Email, - Published: rel.PublishedAt, - Created: rel.CreatedAt, + TagName: rel.TagName, + TargetCommitish: rel.Target, + Name: rel.Title, + Body: rel.Note, + Draft: rel.IsDraft, + Prerelease: rel.IsPrerelease, + PublisherID: rel.Publisher.ID, + PublisherName: rel.Publisher.UserName, + PublisherEmail: rel.Publisher.Email, + Published: rel.PublishedAt, + Created: rel.CreatedAt, } for _, asset := range rel.Attachments { From 9eb83959bdad33f9fa112f4f0c4a8f8b67ab1c09 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 04:58:00 +0200 Subject: [PATCH 05/46] break the Reactions loop --- modules/migrations/gitea_downloader.go | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 362de28957d0..e631d154b946 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -276,21 +276,17 @@ func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, er // getIssueReactions func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, error) { var reactions []*base.Reaction - for i := 1; ; i++ { - rl, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) - if err != nil { - return nil, err - } - if len(rl) == 0 { - break - } - for _, reaction := range rl { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.ID, - UserName: reaction.User.UserName, - Content: reaction.Reaction, - }) - } + rl, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) + if err != nil { + return nil, err + } + + for _, reaction := range rl { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.ID, + UserName: reaction.User.UserName, + Content: reaction.Reaction, + }) } return reactions, nil } From 3d0e606caece324c7f5fbbbdd41d921a81f6a6b2 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 05:54:44 +0200 Subject: [PATCH 06/46] use convertGiteaLabel --- modules/migrations/gitea_downloader.go | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index e631d154b946..4b59a7b2e2c5 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -172,6 +172,14 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { return milestones, nil } +func (g *GiteaDownloader) convertGiteaLabel(label *gitea.Label) *base.Label { + return &base.Label{ + Name: label.Name, + Color: label.Color, + Description: label.Description, + } +} + // GetLabels returns labels func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { if g == nil { @@ -191,11 +199,7 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { } for i := range ls { - labels = append(labels, &base.Label{ - Name: ls[i].Name, - Color: ls[i].Color, - Description: ls[i].Description, - }) + labels = append(labels, g.convertGiteaLabel(ls[i])) } if len(ls) < perPage { break @@ -308,11 +312,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err var labels = make([]*base.Label, 0, len(issue.Labels)) for i := range issue.Labels { - labels = append(labels, &base.Label{ - Name: issue.Labels[i].Name, - Color: issue.Labels[i].Color, - Description: issue.Labels[i].Description, - }) + labels = append(labels, g.convertGiteaLabel(issue.Labels[i])) } var milestone string @@ -415,11 +415,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques var labels = make([]*base.Label, 0, len(pr.Labels)) for i := range pr.Labels { - labels = append(labels, &base.Label{ - Name: pr.Labels[i].Name, - Color: pr.Labels[i].Color, - Description: pr.Labels[i].Description, - }) + labels = append(labels, g.convertGiteaLabel(pr.Labels[i])) } var ( From a80d9d314eaa6d2f6165389a016e362640b1db0a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 16:41:06 +0200 Subject: [PATCH 07/46] fix endless loop because paggination is not supported there !!! --- modules/migrations/gitea_downloader.go | 36 +++++++++++++++++--------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 4b59a7b2e2c5..83f5f7cc8805 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -65,10 +65,11 @@ func (f *GiteaDownloaderFactory) GitServiceType() structs.GitServiceType { // GiteaDownloader implements a Downloader interface to get repository information's type GiteaDownloader struct { - ctx context.Context - client *gitea.Client - repoOwner string - repoName string + ctx context.Context + client *gitea.Client + repoOwner string + repoName string + pagination bool } // NewGiteaDownloader creates a gitea Downloader via gitea API @@ -82,11 +83,17 @@ func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *Gi path := strings.Split(repoPath, "/") + paginationSupport := true + if err := giteaClient.CheckServerVersionConstraint(">=1.12"); err != nil { + paginationSupport = false + } + return &GiteaDownloader{ - ctx: context.Background(), - client: giteaClient, - repoOwner: path[0], - repoName: path[1], + ctx: context.Background(), + client: giteaClient, + repoOwner: path[0], + repoName: path[1], + pagination: paginationSupport, } } @@ -343,7 +350,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err }) } - return allIssues, len(issues) == 0, nil + return allIssues, len(issues) < perPage, nil } // GetComments returns comments according issueNumber @@ -353,6 +360,11 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { var allComments = make([]*base.Comment, 0, 100) for i := 1; ; i++ { + select { + case <-g.ctx.Done(): + return nil, nil + default: + } comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea.ListIssueCommentOptions{ListOptions: gitea.ListOptions{ PageSize: perPage, Page: i, @@ -360,9 +372,7 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { if err != nil { return nil, fmt.Errorf("error while listing comments: %v", err) } - if len(comments) == 0 { - break - } + for _, comment := range comments { rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, comment.ID) if err != nil { @@ -388,6 +398,8 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { Reactions: reactions, }) } + + break //ToDo enable pagination vor (gitea >= 1.13) when it got implemented } return allComments, nil } From 351c3fd2d789d5615a0acffc5485e98f1a0b3d99 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 16:50:25 +0200 Subject: [PATCH 08/46] rename gitea local uploader files --- modules/migrations/{gitea.go => gitea_uploader.go} | 0 modules/migrations/{gitea_test.go => gitea_uploader_test.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename modules/migrations/{gitea.go => gitea_uploader.go} (100%) rename modules/migrations/{gitea_test.go => gitea_uploader_test.go} (100%) diff --git a/modules/migrations/gitea.go b/modules/migrations/gitea_uploader.go similarity index 100% rename from modules/migrations/gitea.go rename to modules/migrations/gitea_uploader.go diff --git a/modules/migrations/gitea_test.go b/modules/migrations/gitea_uploader_test.go similarity index 100% rename from modules/migrations/gitea_test.go rename to modules/migrations/gitea_uploader_test.go From d457206f7c3f6116a8f4ce06ddcbc3bf72930d61 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 17:42:46 +0200 Subject: [PATCH 09/46] pagination can bite you in the ass --- modules/migrations/gitea_downloader.go | 167 +++++++++++++------------ 1 file changed, 88 insertions(+), 79 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 83f5f7cc8805..6b95f12a3f59 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -70,6 +70,7 @@ type GiteaDownloader struct { repoOwner string repoName string pagination bool + maxPerPage int } // NewGiteaDownloader creates a gitea Downloader via gitea API @@ -88,12 +89,18 @@ func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *Gi paginationSupport = false } + // set small maxPerPage since we can only guess (default would be 50 but this can differ) + // safest value would be 1 but this is really inefficient + // ToDo https://github.com/go-gitea/gitea/issues/12664 + maxPerPage := 10 + return &GiteaDownloader{ ctx: context.Background(), client: giteaClient, repoOwner: path[0], repoName: path[1], pagination: paginationSupport, + maxPerPage: maxPerPage, } } @@ -137,13 +144,12 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { if g == nil { return nil, errors.New("error: GiteaDownloader is nil") } - var perPage = 50 - var milestones = make([]*base.Milestone, 0, perPage) + var milestones = make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea.ListMilestoneOption{ ListOptions: gitea.ListOptions{ - PageSize: perPage, + PageSize: g.maxPerPage, Page: i, }, State: gitea.StateAll, @@ -172,7 +178,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { State: string(ms[i].State), }) } - if len(ms) < perPage { + if !g.pagination || len(ms) < g.maxPerPage { break } } @@ -193,12 +199,11 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { return nil, errors.New("error: GiteaDownloader is nil") } - var perPage = 50 - var labels = make([]*base.Label, 0, perPage) + var labels = make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{ - PageSize: perPage, + PageSize: g.maxPerPage, Page: i, }}) if err != nil { @@ -208,7 +213,7 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { for i := range ls { labels = append(labels, g.convertGiteaLabel(ls[i])) } - if len(ls) < perPage { + if !g.pagination || len(ls) < g.maxPerPage { break } } @@ -247,11 +252,10 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea.Release) *base.Release // GetReleases returns releases func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { - var perPage = 100 - var releases = make([]*base.Release, 0, perPage) + var releases = make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea.ListReleasesOptions{ListOptions: gitea.ListOptions{ - PageSize: perPage, + PageSize: g.maxPerPage, Page: i, }}) if err != nil { @@ -261,7 +265,7 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { for i := range rl { releases = append(releases, g.convertGiteaRelease(rl[i])) } - if len(rl) < perPage { + if !g.pagination || len(rl) < g.maxPerPage { break } } @@ -305,6 +309,9 @@ func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, erro // GetIssues returns issues according start and limit func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { + if perPage > g.maxPerPage { + perPage = g.maxPerPage + } var allIssues = make([]*base.Issue, 0, perPage) issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea.ListIssueOption{ @@ -350,63 +357,71 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err }) } + if !g.pagination { // ToDo check since when pagination is supported for issues + return allIssues, true, nil + } return allIssues, len(issues) < perPage, nil } // GetComments returns comments according issueNumber func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { - var perPage = 50 - var allComments = make([]*base.Comment, 0, 100) + var allComments = make([]*base.Comment, 0, g.maxPerPage) - for i := 1; ; i++ { - select { - case <-g.ctx.Done(): - return nil, nil - default: - } - comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea.ListIssueCommentOptions{ListOptions: gitea.ListOptions{ - PageSize: perPage, - Page: i, - }}) + // for i := 1; ; i++ { + select { + case <-g.ctx.Done(): + return nil, nil + default: + } + comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea.ListIssueCommentOptions{ListOptions: gitea.ListOptions{ + // PageSize: g.maxPerPage, + // Page: i, + }}) + if err != nil { + return nil, fmt.Errorf("error while listing comments: %v", err) + } + + for _, comment := range comments { + rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, comment.ID) if err != nil { - return nil, fmt.Errorf("error while listing comments: %v", err) + return nil, err } - - for _, comment := range comments { - rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, comment.ID) - if err != nil { - return nil, err - } - var reactions []*base.Reaction - for i := range rl { - reactions = append(reactions, &base.Reaction{ - UserID: rl[i].User.ID, - UserName: rl[i].User.UserName, - Content: rl[i].Reaction, - }) - } - - allComments = append(allComments, &base.Comment{ - IssueIndex: index, - PosterID: comment.Poster.ID, - PosterName: comment.Poster.UserName, - PosterEmail: comment.Poster.Email, - Content: comment.Body, - Created: comment.Created, - Updated: comment.Updated, - Reactions: reactions, + var reactions []*base.Reaction + for i := range rl { + reactions = append(reactions, &base.Reaction{ + UserID: rl[i].User.ID, + UserName: rl[i].User.UserName, + Content: rl[i].Reaction, }) } - break //ToDo enable pagination vor (gitea >= 1.13) when it got implemented + allComments = append(allComments, &base.Comment{ + IssueIndex: index, + PosterID: comment.Poster.ID, + PosterName: comment.Poster.UserName, + PosterEmail: comment.Poster.Email, + Content: comment.Body, + Created: comment.Created, + Updated: comment.Updated, + Reactions: reactions, + }) } + + // ToDo enable pagination vor (gitea >= 1.13) when it got implemented + // if !g.pagination || len(comments) < g.maxPerPage { + // break + // } + //} return allComments, nil } // GetPullRequests returns pull requests according page and perPage func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { + if perPage > g.maxPerPage { + perPage = g.maxPerPage + } var allPRs = make([]*base.PullRequest, 0, perPage) prs, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea.ListPullRequestsOptions{ @@ -512,13 +527,12 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques // GetReviews returns pull requests review func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { - var perPage = 50 - var allReviews = make([]*base.Review, 0, perPage) + var allReviews = make([]*base.Review, 0, g.maxPerPage) for i := 1; ; i++ { prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea.ListPullReviewsOptions{ListOptions: gitea.ListOptions{ Page: i, - PageSize: perPage, + PageSize: g.maxPerPage, }}) if err != nil { return nil, err @@ -526,33 +540,28 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { for _, pr := range prl { + rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea.ListPullReviewsCommentsOptions{}) + if err != nil { + return nil, err + } var reviewComments []*base.ReviewComment - for ii := 1; ; ii++ { - rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea.ListPullReviewsCommentsOptions{}) - if err != nil { - return nil, err - } - for i := range rcl { - line := int(rcl[i].LineNum) - if rcl[i].OldLineNum > 0 { - line = int(rcl[i].OldLineNum) * -1 - } - - reviewComments = append(reviewComments, &base.ReviewComment{ - ID: rcl[i].ID, - Content: rcl[i].Body, - TreePath: rcl[i].Path, - DiffHunk: rcl[i].DiffHunk, - Position: line, - CommitID: rcl[i].CommitID, - PosterID: rcl[i].Reviewer.ID, - CreatedAt: rcl[i].Created, - UpdatedAt: rcl[i].Updated, - }) - } - if len(rcl) < perPage { - break + for i := range rcl { + line := int(rcl[i].LineNum) + if rcl[i].OldLineNum > 0 { + line = int(rcl[i].OldLineNum) * -1 } + + reviewComments = append(reviewComments, &base.ReviewComment{ + ID: rcl[i].ID, + Content: rcl[i].Body, + TreePath: rcl[i].Path, + DiffHunk: rcl[i].DiffHunk, + Position: line, + CommitID: rcl[i].CommitID, + PosterID: rcl[i].Reviewer.ID, + CreatedAt: rcl[i].Created, + UpdatedAt: rcl[i].Updated, + }) } allReviews = append(allReviews, &base.Review{ @@ -569,7 +578,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { }) } - if len(prl) < perPage { + if len(prl) < g.maxPerPage { break } } From 5ca02fd318288ba56de1904cdd481ebe3b96618c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 18:55:23 +0200 Subject: [PATCH 10/46] Version Checks --- modules/migrations/gitea_downloader.go | 71 +++++++++++++++++++++----- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 6b95f12a3f59..cf950757dd59 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -82,6 +82,13 @@ func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *Gi giteaClient.SetBasicAuth(username, password) } + // do not support gitea instances older that 1.10 + // because 1.10 first got the needed pull & release endpoints + if err := giteaClient.CheckServerVersionConstraint(">=1.10"); err != nil { + log.Error(fmt.Sprintf("NewGiteaDownloader: %s", err.Error())) + return nil + } + path := strings.Split(repoPath, "/") paginationSupport := true @@ -252,6 +259,10 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea.Release) *base.Release // GetReleases returns releases func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + var releases = make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea.ListReleasesOptions{ListOptions: gitea.ListOptions{ @@ -274,6 +285,9 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { // GetAsset returns an asset func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } asset, err := g.client.GetReleaseAttachment(g.repoOwner, g.repoName, relID, id) if err != nil { @@ -288,9 +302,12 @@ func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, er return resp.Body, nil } -// getIssueReactions func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, error) { var reactions []*base.Reaction + if err := g.client.CheckServerVersionConstraint(">=1.11"); err != nil { + log.Info("GiteaDownloader: instance to old, skip getIssueReactions") + return reactions, nil + } rl, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) if err != nil { return nil, err @@ -306,8 +323,32 @@ func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, erro return reactions, nil } +func (g *GiteaDownloader) getCommentReactions(commentID int64) ([]*base.Reaction, error) { + var reactions []*base.Reaction + if err := g.client.CheckServerVersionConstraint(">=1.11"); err != nil { + log.Info("GiteaDownloader: instance to old, skip getCommentReactions") + return reactions, nil + } + rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, commentID) + if err != nil { + return nil, err + } + + for i := range rl { + reactions = append(reactions, &base.Reaction{ + UserID: rl[i].User.ID, + UserName: rl[i].User.UserName, + Content: rl[i].Reaction, + }) + } + return reactions, nil +} + // GetIssues returns issues according start and limit func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { + if g == nil { + return nil, true, errors.New("error: GiteaDownloader is nil") + } if perPage > g.maxPerPage { perPage = g.maxPerPage @@ -357,14 +398,14 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err }) } - if !g.pagination { // ToDo check since when pagination is supported for issues - return allIssues, true, nil - } return allIssues, len(issues) < perPage, nil } // GetComments returns comments according issueNumber func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } var allComments = make([]*base.Comment, 0, g.maxPerPage) @@ -383,17 +424,9 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { } for _, comment := range comments { - rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, comment.ID) + reactions, err := g.getCommentReactions(comment.ID) if err != nil { - return nil, err - } - var reactions []*base.Reaction - for i := range rl { - reactions = append(reactions, &base.Reaction{ - UserID: rl[i].User.ID, - UserName: rl[i].User.UserName, - Content: rl[i].Reaction, - }) + return nil, fmt.Errorf("error while listing comment creactions: %v", err) } allComments = append(allComments, &base.Comment{ @@ -418,6 +451,9 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { // GetPullRequests returns pull requests according page and perPage func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } if perPage > g.maxPerPage { perPage = g.maxPerPage @@ -526,6 +562,13 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques // GetReviews returns pull requests review func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { + if g == nil { + return nil, errors.New("error: GiteaDownloader is nil") + } + if err := g.client.CheckServerVersionConstraint(">=1.12"); err != nil { + log.Info("GiteaDownloader: instance to old, skip GetReviews") + return nil, nil + } var allReviews = make([]*base.Review, 0, g.maxPerPage) From da84e835fb1a00f3367305dafa148cca90e55b4c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 19:20:22 +0200 Subject: [PATCH 11/46] lint --- modules/migrations/gitea_downloader.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index cf950757dd59..63caba1288fc 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -377,7 +377,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err reactions, err := g.getIssueReactions(issue.Index) if err != nil { - return nil, false, fmt.Errorf("error while geting reactions: %v", err) + return nil, false, fmt.Errorf("error while loading reactions: %v", err) } allIssues = append(allIssues, &base.Issue{ @@ -504,7 +504,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques reactions, err := g.getIssueReactions(pr.Index) if err != nil { - return nil, fmt.Errorf("error while geting reactions: %v", err) + return nil, fmt.Errorf("error while loading reactions: %v", err) } var assignees []string From 7da46b73fab6f91da39615248263ff6ae04ba353 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 19:30:02 +0200 Subject: [PATCH 12/46] docs --- modules/migrations/gitea_downloader.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 63caba1288fc..c903dc6a849e 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -74,7 +74,7 @@ type GiteaDownloader struct { } // NewGiteaDownloader creates a gitea Downloader via gitea API -// Use either a username/password, personal token entered into the username field, or anonymous/public access +// Use either a username/password or personal token. token is preferred // Note: Public access only allows very basic access func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *GiteaDownloader { giteaClient := gitea.NewClient(baseURL, token) @@ -83,7 +83,7 @@ func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *Gi } // do not support gitea instances older that 1.10 - // because 1.10 first got the needed pull & release endpoints + // because gitea v1.10.0 first got the needed pull & release endpoints if err := giteaClient.CheckServerVersionConstraint(">=1.10"); err != nil { log.Error(fmt.Sprintf("NewGiteaDownloader: %s", err.Error())) return nil From f792c3ec25386afdc294547b2afffa9303bbc5cd Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 20:21:03 +0200 Subject: [PATCH 13/46] rename gitea sdk import to miss future conficts --- modules/migrations/gitea_downloader.go | 42 +++++++++++++------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index c903dc6a849e..6d54f683ba10 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -18,7 +18,7 @@ import ( "code.gitea.io/gitea/modules/migrations/base" "code.gitea.io/gitea/modules/structs" - "code.gitea.io/sdk/gitea" + gitea_sdk "code.gitea.io/sdk/gitea" ) var ( @@ -66,7 +66,7 @@ func (f *GiteaDownloaderFactory) GitServiceType() structs.GitServiceType { // GiteaDownloader implements a Downloader interface to get repository information's type GiteaDownloader struct { ctx context.Context - client *gitea.Client + client *gitea_sdk.Client repoOwner string repoName string pagination bool @@ -77,7 +77,7 @@ type GiteaDownloader struct { // Use either a username/password or personal token. token is preferred // Note: Public access only allows very basic access func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *GiteaDownloader { - giteaClient := gitea.NewClient(baseURL, token) + giteaClient := gitea_sdk.NewClient(baseURL, token) if token == "" { giteaClient.SetBasicAuth(username, password) } @@ -143,7 +143,7 @@ func (g *GiteaDownloader) GetTopics() ([]string, error) { return nil, errors.New("error: GiteaDownloader is nil") } - return g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea.ListRepoTopicsOptions{}) + return g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea_sdk.ListRepoTopicsOptions{}) } // GetMilestones returns milestones @@ -154,12 +154,12 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { var milestones = make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { - ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea.ListMilestoneOption{ - ListOptions: gitea.ListOptions{ + ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea_sdk.ListMilestoneOption{ + ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, }, - State: gitea.StateAll, + State: gitea_sdk.StateAll, }) if err != nil { return nil, err @@ -192,7 +192,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { return milestones, nil } -func (g *GiteaDownloader) convertGiteaLabel(label *gitea.Label) *base.Label { +func (g *GiteaDownloader) convertGiteaLabel(label *gitea_sdk.Label) *base.Label { return &base.Label{ Name: label.Name, Color: label.Color, @@ -209,7 +209,7 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { var labels = make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { - ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea.ListLabelsOptions{ListOptions: gitea.ListOptions{ + ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea_sdk.ListLabelsOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, }}) @@ -227,7 +227,7 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { return labels, nil } -func (g *GiteaDownloader) convertGiteaRelease(rel *gitea.Release) *base.Release { +func (g *GiteaDownloader) convertGiteaRelease(rel *gitea_sdk.Release) *base.Release { r := &base.Release{ TagName: rel.TagName, TargetCommitish: rel.Target, @@ -265,7 +265,7 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { var releases = make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { - rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea.ListReleasesOptions{ListOptions: gitea.ListOptions{ + rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea_sdk.ListReleasesOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, }}) @@ -355,10 +355,10 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err } var allIssues = make([]*base.Issue, 0, perPage) - issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea.ListIssueOption{ - ListOptions: gitea.ListOptions{Page: page, PageSize: perPage}, - State: gitea.StateAll, - Type: gitea.IssueTypeIssue, + issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea_sdk.ListIssueOption{ + ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: perPage}, + State: gitea_sdk.StateAll, + Type: gitea_sdk.IssueTypeIssue, }) if err != nil { return nil, false, fmt.Errorf("error while listing issues: %v", err) @@ -415,7 +415,7 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { return nil, nil default: } - comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea.ListIssueCommentOptions{ListOptions: gitea.ListOptions{ + comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea_sdk.ListIssueCommentOptions{ListOptions: gitea_sdk.ListOptions{ // PageSize: g.maxPerPage, // Page: i, }}) @@ -460,12 +460,12 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques } var allPRs = make([]*base.PullRequest, 0, perPage) - prs, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea.ListPullRequestsOptions{ - ListOptions: gitea.ListOptions{ + prs, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea_sdk.ListPullRequestsOptions{ + ListOptions: gitea_sdk.ListOptions{ Page: page, PageSize: perPage, }, - State: gitea.StateAll, + State: gitea_sdk.StateAll, }) if err != nil { return nil, fmt.Errorf("error while listing repos: %v", err) @@ -573,7 +573,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { var allReviews = make([]*base.Review, 0, g.maxPerPage) for i := 1; ; i++ { - prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea.ListPullReviewsOptions{ListOptions: gitea.ListOptions{ + prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea_sdk.ListPullReviewsOptions{ListOptions: gitea_sdk.ListOptions{ Page: i, PageSize: g.maxPerPage, }}) @@ -583,7 +583,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { for _, pr := range prl { - rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea.ListPullReviewsCommentsOptions{}) + rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea_sdk.ListPullReviewsCommentsOptions{}) if err != nil { return nil, err } From a7db7df453c95727a0cc63d54a8765fcef29b62f Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 20:21:39 +0200 Subject: [PATCH 14/46] go-swagger: dont scan the sdk structs --- Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 1fec4eb503ca..4698d65be67f 100644 --- a/Makefile +++ b/Makefile @@ -120,11 +120,12 @@ endif GO_SOURCES_OWN := $(filter-out vendor/% %/bindata.go, $(GO_SOURCES)) -#To update swagger use: GO111MODULE=on go get -u github.com/go-swagger/go-swagger/cmd/swagger@v0.20.1 +#To update swagger use: GO111MODULE=on go get -u github.com/go-swagger/go-swagger/cmd/swagger SWAGGER := $(GO) run -mod=vendor github.com/go-swagger/go-swagger/cmd/swagger SWAGGER_SPEC := templates/swagger/v1_json.tmpl SWAGGER_SPEC_S_TMPL := s|"basePath": *"/api/v1"|"basePath": "{{AppSubUrl}}/api/v1"|g SWAGGER_SPEC_S_JSON := s|"basePath": *"{{AppSubUrl}}/api/v1"|"basePath": "/api/v1"|g +SWAGGER_EXCLUDE := code.gitea.io/sdk SWAGGER_NEWLINE_COMMAND := -e '$$a\' TEST_MYSQL_HOST ?= mysql:3306 @@ -240,7 +241,7 @@ endif .PHONY: generate-swagger generate-swagger: - $(SWAGGER) generate spec -o './$(SWAGGER_SPEC)' + $(SWAGGER) generate spec -x "$(SWAGGER_EXCLUDE)" -o './$(SWAGGER_SPEC)' $(SED_INPLACE) '$(SWAGGER_SPEC_S_TMPL)' './$(SWAGGER_SPEC)' $(SED_INPLACE) $(SWAGGER_NEWLINE_COMMAND) './$(SWAGGER_SPEC)' From 53462b97b26771fdc7b7b2deba1b4dd4621db1c0 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 20:47:19 +0200 Subject: [PATCH 15/46] make sure gitea can shutdown gracefully --- modules/migrations/gitea_downloader.go | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 6d54f683ba10..b8da0f7c2bd6 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -154,6 +154,13 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { var milestones = make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { + // make sure gitea can shutdown gracefully + select { + case <-g.ctx.Done(): + return nil, nil + default: + } + ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea_sdk.ListMilestoneOption{ ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, @@ -209,6 +216,13 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { var labels = make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { + // make sure gitea can shutdown gracefully + select { + case <-g.ctx.Done(): + return nil, nil + default: + } + ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea_sdk.ListLabelsOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, @@ -265,6 +279,13 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { var releases = make([]*base.Release, 0, g.maxPerPage) for i := 1; ; i++ { + // make sure gitea can shutdown gracefully + select { + case <-g.ctx.Done(): + return nil, nil + default: + } + rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea_sdk.ListReleasesOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, @@ -410,11 +431,13 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { var allComments = make([]*base.Comment, 0, g.maxPerPage) // for i := 1; ; i++ { + // make sure gitea can shutdown gracefully select { case <-g.ctx.Done(): return nil, nil default: } + comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea_sdk.ListIssueCommentOptions{ListOptions: gitea_sdk.ListOptions{ // PageSize: g.maxPerPage, // Page: i, @@ -573,6 +596,13 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { var allReviews = make([]*base.Review, 0, g.maxPerPage) for i := 1; ; i++ { + // make sure gitea can shutdown gracefully + select { + case <-g.ctx.Done(): + return nil, nil + default: + } + prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea_sdk.ListPullReviewsOptions{ListOptions: gitea_sdk.ListOptions{ Page: i, PageSize: g.maxPerPage, From 81f7723e4ee648914d79f4d45a1caafc066ee079 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 31 Aug 2020 21:08:20 +0200 Subject: [PATCH 16/46] make GetPullRequests and GetIssues similar --- modules/migrations/base/downloader.go | 11 ++++++----- modules/migrations/git.go | 4 ++-- modules/migrations/gitea_downloader.go | 10 +++++----- modules/migrations/github.go | 8 ++++---- modules/migrations/github_test.go | 2 +- modules/migrations/gitlab.go | 6 +++--- modules/migrations/gitlab_test.go | 2 +- modules/migrations/migrate.go | 4 ++-- 8 files changed, 24 insertions(+), 23 deletions(-) diff --git a/modules/migrations/base/downloader.go b/modules/migrations/base/downloader.go index ae12e6083c86..49eb5370e166 100644 --- a/modules/migrations/base/downloader.go +++ b/modules/migrations/base/downloader.go @@ -29,7 +29,7 @@ type Downloader interface { GetLabels() ([]*Label, error) GetIssues(page, perPage int) ([]*Issue, bool, error) GetComments(issueNumber int64) ([]*Comment, error) - GetPullRequests(page, perPage int) ([]*PullRequest, error) + GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) GetReviews(pullRequestNumber int64) ([]*Review, error) } @@ -178,19 +178,20 @@ func (d *RetryDownloader) GetComments(issueNumber int64) ([]*Comment, error) { } // GetPullRequests returns a repository's pull requests with retry -func (d *RetryDownloader) GetPullRequests(page, perPage int) ([]*PullRequest, error) { +func (d *RetryDownloader) GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) { var ( times = d.RetryTimes prs []*PullRequest err error + isEnd bool ) for ; times > 0; times-- { - if prs, err = d.Downloader.GetPullRequests(page, perPage); err == nil { - return prs, nil + if prs, isEnd, err = d.Downloader.GetPullRequests(page, perPage); err == nil { + return prs, isEnd, nil } time.Sleep(time.Second * time.Duration(d.RetryDelay)) } - return nil, err + return nil, false, err } // GetReviews returns pull requests reviews diff --git a/modules/migrations/git.go b/modules/migrations/git.go index 7128ee60c2af..0aad8dbef5bb 100644 --- a/modules/migrations/git.go +++ b/modules/migrations/git.go @@ -81,8 +81,8 @@ func (g *PlainGitDownloader) GetComments(issueNumber int64) ([]*base.Comment, er } // GetPullRequests returns pull requests according page and perPage -func (g *PlainGitDownloader) GetPullRequests(start, limit int) ([]*base.PullRequest, error) { - return nil, ErrNotSupported +func (g *PlainGitDownloader) GetPullRequests(start, limit int) ([]*base.PullRequest, bool, error) { + return nil, false, ErrNotSupported } // GetReviews returns reviews according issue number diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index b8da0f7c2bd6..82c590ace818 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -473,9 +473,9 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { } // GetPullRequests returns pull requests according page and perPage -func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { +func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") + return nil, false, errors.New("error: GiteaDownloader is nil") } if perPage > g.maxPerPage { @@ -491,7 +491,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques State: gitea_sdk.StateAll, }) if err != nil { - return nil, fmt.Errorf("error while listing repos: %v", err) + return nil, false, fmt.Errorf("error while listing repos: %v", err) } for _, pr := range prs { var milestone string @@ -527,7 +527,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques reactions, err := g.getIssueReactions(pr.Index) if err != nil { - return nil, fmt.Errorf("error while loading reactions: %v", err) + return nil, false, fmt.Errorf("error while loading reactions: %v", err) } var assignees []string @@ -580,7 +580,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques }) } - return allPRs, nil + return allPRs, len(prs) < perPage, nil } // GetReviews returns pull requests review diff --git a/modules/migrations/github.go b/modules/migrations/github.go index e322171614ee..2fcbda310774 100644 --- a/modules/migrations/github.go +++ b/modules/migrations/github.go @@ -486,7 +486,7 @@ func (g *GithubDownloaderV3) GetComments(issueNumber int64) ([]*base.Comment, er } // GetPullRequests returns pull requests according page and perPage -func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { +func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { opt := &github.PullRequestListOptions{ Sort: "created", Direction: "asc", @@ -500,7 +500,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq g.sleep() prs, resp, err := g.client.PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt) if err != nil { - return nil, fmt.Errorf("error while listing repos: %v", err) + return nil, false, fmt.Errorf("error while listing repos: %v", err) } g.rate = &resp.Rate for _, pr := range prs { @@ -566,7 +566,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq PerPage: perPage, }) if err != nil { - return nil, err + return nil, false, err } g.rate = &resp.Rate if len(res) == 0 { @@ -616,7 +616,7 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq }) } - return allPRs, nil + return allPRs, len(prs) < perPage, nil } func convertGithubReview(r *github.PullRequestReview) *base.Review { diff --git a/modules/migrations/github_test.go b/modules/migrations/github_test.go index 0b8c559d305f..617a57455027 100644 --- a/modules/migrations/github_test.go +++ b/modules/migrations/github_test.go @@ -269,7 +269,7 @@ func TestGitHubDownloadRepo(t *testing.T) { }, comments[:2]) // downloader.GetPullRequests() - prs, err := downloader.GetPullRequests(1, 2) + prs, _, err := downloader.GetPullRequests(1, 2) assert.NoError(t, err) assert.EqualValues(t, 2, len(prs)) diff --git a/modules/migrations/gitlab.go b/modules/migrations/gitlab.go index 7fc3fab0ec0e..d504ed5f95d2 100644 --- a/modules/migrations/gitlab.go +++ b/modules/migrations/gitlab.go @@ -441,7 +441,7 @@ func (g *GitlabDownloader) GetComments(issueNumber int64) ([]*base.Comment, erro } // GetPullRequests returns pull requests according page and perPage -func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) { +func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { opt := &gitlab.ListProjectMergeRequestsOptions{ ListOptions: gitlab.ListOptions{ @@ -457,7 +457,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque prs, _, err := g.client.MergeRequests.ListProjectMergeRequests(g.repoID, opt, nil) if err != nil { - return nil, fmt.Errorf("error while listing merge requests: %v", err) + return nil, false, fmt.Errorf("error while listing merge requests: %v", err) } for _, pr := range prs { @@ -530,7 +530,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque }) } - return allPRs, nil + return allPRs, len(prs) < perPage, nil } // GetReviews returns pull requests review diff --git a/modules/migrations/gitlab_test.go b/modules/migrations/gitlab_test.go index daf05f8e3a6f..cf445e171bf4 100644 --- a/modules/migrations/gitlab_test.go +++ b/modules/migrations/gitlab_test.go @@ -200,7 +200,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, }, comments[:4]) - prs, err := downloader.GetPullRequests(1, 1) + prs, _, err := downloader.GetPullRequests(1, 1) assert.NoError(t, err) assert.Len(t, prs, 1) diff --git a/modules/migrations/migrate.go b/modules/migrations/migrate.go index 7858dfc6850c..b27e7125b57b 100644 --- a/modules/migrations/migrate.go +++ b/modules/migrations/migrate.go @@ -231,7 +231,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts log.Trace("migrating pull requests and comments") var prBatchSize = uploader.MaxBatchInsertSize("pullrequest") for i := 1; ; i++ { - prs, err := downloader.GetPullRequests(i, prBatchSize) + prs, isEnd, err := downloader.GetPullRequests(i, prBatchSize) if err != nil { return err } @@ -302,7 +302,7 @@ func migrateRepository(downloader base.Downloader, uploader base.Uploader, opts } } - if len(prs) < prBatchSize { + if isEnd { break } } From 47e7d16bc20cda9099b669508ab5198afc3b5e85 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 1 Sep 2020 03:29:51 +0200 Subject: [PATCH 17/46] rm useles --- modules/migrations/base/repo.go | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/modules/migrations/base/repo.go b/modules/migrations/base/repo.go index 5cfb0de920db..764c9e8d8602 100644 --- a/modules/migrations/base/repo.go +++ b/modules/migrations/base/repo.go @@ -7,13 +7,11 @@ package base // Repository defines a standard repository information type Repository struct { - Name string - Owner string - IsPrivate bool - IsMirror bool - Description string - AuthUsername string - AuthPassword string - CloneURL string - OriginalURL string + Name string + Owner string + IsPrivate bool + IsMirror bool + Description string + CloneURL string + OriginalURL string } From 97ea19e34c6befb97c1e4f504b4639695fa466f6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 1 Sep 2020 03:35:43 +0200 Subject: [PATCH 18/46] Add Test: started ... --- modules/migrations/gitea_downloader_test.go | 85 +++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 modules/migrations/gitea_downloader_test.go diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go new file mode 100644 index 000000000000..249151d41c2c --- /dev/null +++ b/modules/migrations/gitea_downloader_test.go @@ -0,0 +1,85 @@ +// 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 migrations + +import ( + "fmt" + "net/http" + "os" + "sort" + "testing" + + "code.gitea.io/gitea/modules/migrations/base" + + "github.com/stretchr/testify/assert" +) + +func TestGiteaDownloadRepo(t *testing.T) { + // Skip tests if Gitea token is not found + giteaToken := os.Getenv("GITEA_TOKEN") + if giteaToken == "" { + t.Skip("skipped test because GITEA_TOKEN was not in the environment") + } + + resp, err := http.Get("https://gitea.com/gitea") + if err != nil || resp.StatusCode != 200 { + t.Skipf("Can't access test repo, skipping %s", t.Name()) + } + + downloader := NewGiteaDownloader("https://gitea.com", "6543/test_repo", "", "", giteaToken) + if downloader == nil { + t.Fatal("NewGitlabDownloader is nil") + } + + repo, err := downloader.GetRepoInfo() + assert.NoError(t, err) + assert.EqualValues(t, &base.Repository{ + Name: "test_repo", + Owner: "6543", + IsPrivate: false, // ToDo: set test repo private + Description: "Test repository for testing migration from gitea to gitea", + CloneURL: "https://gitea.com/6543/test_repo.git", + OriginalURL: "https://gitea.com/6543/test_repo", + }, repo) + + topics, err := downloader.GetTopics() + assert.NoError(t, err) + sort.Strings(topics) + assert.EqualValues(t, []string{"ci", "gitea", "migration", "test"}, topics) + + labels, err := downloader.GetLabels() + assert.NoError(t, err) + assert.Len(t, labels, 6) + for _, l := range labels { + switch l.Name { + case "Bug": + assertLabelEqual(t, "Bug", "e11d21", "", l) + case "documentation": + assertLabelEqual(t, "Enhancement", "207de5", "", l) + case "confirmed": + assertLabelEqual(t, "Feature", "0052cc", "a feature request", l) + case "enhancement": + assertLabelEqual(t, "Invalid", "d4c5f9", "", l) + case "critical": + assertLabelEqual(t, "Question", "fbca04", "", l) + case "discussion": + assertLabelEqual(t, "Valid", "53e917", "", l) + default: + assert.Error(t, fmt.Errorf("unexpected label: %s", l.Name)) + } + } + + /* + ToDo: + GetAsset(relTag string, relID, id int64) (io.ReadCloser, error) + GetMilestones() ([]*Milestone, error) + GetReleases() ([]*Release, error) + GetIssues(page, perPage int) ([]*Issue, bool, error) + GetComments(issueNumber int64) ([]*Comment, error) + GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) + GetReviews(pullRequestNumber int64) ([]*Review, error) + */ + +} From cfcaeef96d7cdd5f97253f2ad76e4a4f86ee9490 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 1 Sep 2020 22:38:10 +0200 Subject: [PATCH 19/46] ... add tests ... --- modules/migrations/gitea_downloader.go | 12 +- modules/migrations/gitea_downloader_test.go | 159 ++++++++++++++++++-- 2 files changed, 160 insertions(+), 11 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 82c590ace818..9ae464820e45 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -419,7 +419,11 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err }) } - return allIssues, len(issues) < perPage, nil + isEnd := len(issues) < perPage + if !g.pagination { + isEnd = len(issues) == 0 + } + return allIssues, isEnd, nil } // GetComments returns comments according issueNumber @@ -580,7 +584,11 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques }) } - return allPRs, len(prs) < perPage, nil + isEnd := len(prs) < perPage + if !g.pagination { + isEnd = len(prs) == 0 + } + return allPRs, isEnd, nil } // GetReviews returns pull requests review diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 249151d41c2c..390515b79296 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -10,12 +10,33 @@ import ( "os" "sort" "testing" + "time" "code.gitea.io/gitea/modules/migrations/base" "github.com/stretchr/testify/assert" ) +func assertEqualIssue(t *testing.T, issueExp, IssueGet *base.Issue) { + assert.EqualValues(t, issueExp.Number, IssueGet.Number) + assert.EqualValues(t, issueExp.Title, IssueGet.Title) + assert.EqualValues(t, issueExp.Content, IssueGet.Content) + assert.EqualValues(t, issueExp.Milestone, IssueGet.Milestone) + assert.EqualValues(t, issueExp.PosterID, IssueGet.PosterID) + assert.EqualValues(t, issueExp.PosterName, IssueGet.PosterName) + assert.EqualValues(t, issueExp.PosterEmail, IssueGet.PosterEmail) + assert.EqualValues(t, issueExp.IsLocked, IssueGet.IsLocked) + assert.EqualValues(t, issueExp.Created.Unix(), IssueGet.Created.Unix()) + assert.EqualValues(t, issueExp.Updated.Unix(), IssueGet.Updated.Unix()) + if issueExp.Closed != nil { + assert.EqualValues(t, issueExp.Closed.Unix(), IssueGet.Closed.Unix()) + } else { + assert.True(t, IssueGet.Closed == nil) + } + assert.EqualValues(t, issueExp.Labels, IssueGet.Labels) + assert.EqualValues(t, issueExp.Reactions, IssueGet.Reactions) +} + func TestGiteaDownloadRepo(t *testing.T) { // Skip tests if Gitea token is not found giteaToken := os.Getenv("GITEA_TOKEN") @@ -25,10 +46,10 @@ func TestGiteaDownloadRepo(t *testing.T) { resp, err := http.Get("https://gitea.com/gitea") if err != nil || resp.StatusCode != 200 { - t.Skipf("Can't access test repo, skipping %s", t.Name()) + t.Skipf("Can't reach https://gitea.com, skipping %s", t.Name()) } - downloader := NewGiteaDownloader("https://gitea.com", "6543/test_repo", "", "", giteaToken) + downloader := NewGiteaDownloader("https://gitea.com", "gitea/test_repo", "", "", giteaToken) if downloader == nil { t.Fatal("NewGitlabDownloader is nil") } @@ -37,11 +58,11 @@ func TestGiteaDownloadRepo(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, &base.Repository{ Name: "test_repo", - Owner: "6543", + Owner: "gitea", IsPrivate: false, // ToDo: set test repo private Description: "Test repository for testing migration from gitea to gitea", - CloneURL: "https://gitea.com/6543/test_repo.git", - OriginalURL: "https://gitea.com/6543/test_repo", + CloneURL: "https://gitea.com/gitea/test_repo.git", + OriginalURL: "https://gitea.com/gitea/test_repo", }, repo) topics, err := downloader.GetTopics() @@ -71,12 +92,132 @@ func TestGiteaDownloadRepo(t *testing.T) { } } + milestones, err := downloader.GetMilestones() + assert.NoError(t, err) + assert.Len(t, milestones, 2) + + for _, milestone := range milestones { + switch milestone.Title { + case "V1": + assert.EqualValues(t, "Generate Content", milestone.Description) + // assert.EqualValues(t, "ToDo", milestone.Created) + // assert.EqualValues(t, "ToDo", milestone.Updated) + assert.EqualValues(t, 1598985406, milestone.Closed.Unix()) + assert.True(t, milestone.Deadline == nil) + assert.EqualValues(t, "closed", milestone.State) + case "V2 Finalize": + assert.EqualValues(t, "", milestone.Description) + // assert.EqualValues(t, "ToDo", milestone.Created) + // assert.EqualValues(t, "ToDo", milestone.Updated) + assert.True(t, milestone.Closed == nil) + assert.EqualValues(t, 1599263999, milestone.Deadline.Unix()) + assert.EqualValues(t, "open", milestone.State) + default: + assert.Error(t, fmt.Errorf("unexpected milestone: %s", milestone.Title)) + } + } + + releases, err := downloader.GetReleases() + assert.NoError(t, err) + assert.EqualValues(t, []*base.Release{ + { + Name: "Second Release", + TagName: "v2-rc1", + TargetCommitish: "master", + Body: "this repo has:\r\n* reactions\r\n* wiki\r\n* issues (open/closed)\r\n* pulls (open/closed/merged) (external/internal)\r\n* pull reviews\r\n* projects\r\n* milestones\r\n* lables\r\n* releases\r\n\r\nto test migration agains", + Draft: false, + Prerelease: true, + Created: time.Date(2020, 9, 1, 18, 2, 43, 0, time.UTC), + Published: time.Date(2020, 9, 1, 18, 2, 43, 0, time.UTC), + PublisherID: 689, + PublisherName: "6543", + PublisherEmail: "6543@noreply.gitea.io", + }, + { + Name: "First Release", + TagName: "V1", + TargetCommitish: "master", + Body: "as title", + Draft: false, + Prerelease: false, + Created: time.Date(2020, 9, 1, 17, 30, 32, 0, time.UTC), + Published: time.Date(2020, 9, 1, 17, 30, 32, 0, time.UTC), + PublisherID: 689, + PublisherName: "6543", + PublisherEmail: "6543@noreply.gitea.io", + }, + }, releases) + + issues, isEnd, err := downloader.GetIssues(1, 50) + assert.NoError(t, err) + assert.EqualValues(t, 7, len(issues)) + assert.True(t, isEnd) + assert.EqualValues(t, "open", issues[0].State) + + issues, isEnd, err = downloader.GetIssues(3, 2) + assert.NoError(t, err) + assert.EqualValues(t, 2, len(issues)) + assert.False(t, isEnd) + + var ( + closed4 = time.Date(2020, 9, 1, 15, 49, 34, 0, time.UTC) + closed2 = time.Unix(1598969497, 0) + ) + + assertEqualIssue(t, &base.Issue{ + Number: 4, + Title: "what is this repo about?", + Content: "", + Milestone: "V1", + PosterID: -1, + PosterName: "Ghost", + PosterEmail: "", + State: "closed", + IsLocked: true, + Created: time.Unix(1598975321, 0), + Updated: time.Unix(1598975400, 0), + Labels: []*base.Label{{ + Name: "Question", + Color: "fbca04", + Description: "", + }}, + Reactions: []*base.Reaction{ + { + UserID: 689, + UserName: "6543", + Content: "gitea", + }, + { + UserID: 689, + UserName: "6543", + Content: "laugh", + }, + }, + Closed: &closed4, + }, issues[0]) + assertEqualIssue(t, &base.Issue{ + Number: 2, + Title: "Spam", + Content: ":(", + Milestone: "", + PosterID: 689, + PosterName: "6543", + PosterEmail: "6543@noreply.gitea.io", + State: "closed", + IsLocked: false, + Created: time.Unix(1598919780, 0), + Updated: closed2, + Labels: []*base.Label{{ + Name: "Invalid", + Color: "d4c5f9", + Description: "", + }}, + Reactions: nil, + Closed: &closed2, + }, issues[1]) + /* ToDo: - GetAsset(relTag string, relID, id int64) (io.ReadCloser, error) - GetMilestones() ([]*Milestone, error) - GetReleases() ([]*Release, error) - GetIssues(page, perPage int) ([]*Issue, bool, error) GetComments(issueNumber int64) ([]*Comment, error) GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) GetReviews(pullRequestNumber int64) ([]*Review, error) From 7de2def485f5880fdee4804c22e244430f7f2b8f Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 2 Sep 2020 06:23:25 +0200 Subject: [PATCH 20/46] Add tests and Fixing things --- modules/migrations/base/issue.go | 1 + modules/migrations/gitea_downloader.go | 17 ++- modules/migrations/gitea_downloader_test.go | 146 +++++++++++++++++--- 3 files changed, 142 insertions(+), 22 deletions(-) diff --git a/modules/migrations/base/issue.go b/modules/migrations/base/issue.go index 4e2bf25f1772..b9625a23f6cd 100644 --- a/modules/migrations/base/issue.go +++ b/modules/migrations/base/issue.go @@ -23,4 +23,5 @@ type Issue struct { Closed *time.Time Labels []*Label Reactions []*Reaction + Assignees []string } diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 9ae464820e45..d1c44e9294b6 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -401,6 +401,11 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err return nil, false, fmt.Errorf("error while loading reactions: %v", err) } + var assignees []string + for i := range issue.Assignees { + assignees = append(assignees, issue.Assignees[i].UserName) + } + allIssues = append(allIssues, &base.Issue{ Title: issue.Title, Number: issue.Index, @@ -415,6 +420,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err Closed: issue.Closed, Reactions: reactions, Labels: labels, + Assignees: assignees, IsLocked: issue.IsLocked, }) } @@ -519,9 +525,13 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques if pr.Head.Repository != nil { headUserName = pr.Head.Repository.Owner.UserName headRepoName = pr.Head.Repository.Name + headCloneURL = pr.Head.Repository.CloneURL } headSHA = pr.Head.Sha headRef = pr.Head.Ref + if headSHA == "" { + // ToDo: !!! ned get headSHA workaround + } } var mergeCommitSHA string @@ -548,6 +558,11 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques updatedAt = *pr.Updated } + closedAt := pr.Closed + if pr.Merged != nil && closedAt == nil { + closedAt = pr.Merged + } + allPRs = append(allPRs, &base.PullRequest{ Title: pr.Title, Number: pr.Index, @@ -558,7 +573,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques State: string(pr.State), Created: createdAt, Updated: updatedAt, - Closed: pr.Closed, + Closed: closedAt, Labels: labels, Milestone: milestone, Reactions: reactions, diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 390515b79296..40274e8f1e24 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -17,24 +17,27 @@ import ( "github.com/stretchr/testify/assert" ) -func assertEqualIssue(t *testing.T, issueExp, IssueGet *base.Issue) { - assert.EqualValues(t, issueExp.Number, IssueGet.Number) - assert.EqualValues(t, issueExp.Title, IssueGet.Title) - assert.EqualValues(t, issueExp.Content, IssueGet.Content) - assert.EqualValues(t, issueExp.Milestone, IssueGet.Milestone) - assert.EqualValues(t, issueExp.PosterID, IssueGet.PosterID) - assert.EqualValues(t, issueExp.PosterName, IssueGet.PosterName) - assert.EqualValues(t, issueExp.PosterEmail, IssueGet.PosterEmail) - assert.EqualValues(t, issueExp.IsLocked, IssueGet.IsLocked) - assert.EqualValues(t, issueExp.Created.Unix(), IssueGet.Created.Unix()) - assert.EqualValues(t, issueExp.Updated.Unix(), IssueGet.Updated.Unix()) +func assertEqualIssue(t *testing.T, issueExp, issueGet *base.Issue) { + assert.EqualValues(t, issueExp.Number, issueGet.Number) + assert.EqualValues(t, issueExp.Title, issueGet.Title) + assert.EqualValues(t, issueExp.Content, issueGet.Content) + assert.EqualValues(t, issueExp.Milestone, issueGet.Milestone) + assert.EqualValues(t, issueExp.PosterID, issueGet.PosterID) + assert.EqualValues(t, issueExp.PosterName, issueGet.PosterName) + assert.EqualValues(t, issueExp.PosterEmail, issueGet.PosterEmail) + assert.EqualValues(t, issueExp.IsLocked, issueGet.IsLocked) + assert.EqualValues(t, issueExp.Created.Unix(), issueGet.Created.Unix()) + assert.EqualValues(t, issueExp.Updated.Unix(), issueGet.Updated.Unix()) if issueExp.Closed != nil { - assert.EqualValues(t, issueExp.Closed.Unix(), IssueGet.Closed.Unix()) + assert.EqualValues(t, issueExp.Closed.Unix(), issueGet.Closed.Unix()) } else { - assert.True(t, IssueGet.Closed == nil) + assert.True(t, issueGet.Closed == nil) } - assert.EqualValues(t, issueExp.Labels, IssueGet.Labels) - assert.EqualValues(t, issueExp.Reactions, IssueGet.Reactions) + sort.Strings(issueExp.Assignees) + sort.Strings(issueGet.Assignees) + assert.EqualValues(t, issueExp.Assignees, issueGet.Assignees) + assert.EqualValues(t, issueExp.Labels, issueGet.Labels) + assert.EqualValues(t, issueExp.Reactions, issueGet.Reactions) } func TestGiteaDownloadRepo(t *testing.T) { @@ -216,11 +219,112 @@ func TestGiteaDownloadRepo(t *testing.T) { Closed: &closed2, }, issues[1]) - /* - ToDo: - GetComments(issueNumber int64) ([]*Comment, error) - GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) - GetReviews(pullRequestNumber int64) ([]*Review, error) - */ + comments, err := downloader.GetComments(4) + assert.NoError(t, err) + assert.Len(t, comments, 2) + assert.EqualValues(t, 1598975370, comments[0].Created.Unix()) + assert.EqualValues(t, 1598975370, comments[0].Updated.Unix()) + assert.EqualValues(t, 1598975393, comments[1].Created.Unix()) + assert.EqualValues(t, 1598975393, comments[1].Updated.Unix()) + assert.EqualValues(t, []*base.Comment{ + { + IssueIndex: 4, + PosterID: 689, + PosterName: "6543", + PosterEmail: "6543@noreply.gitea.io", + Created: comments[0].Created, + Updated: comments[0].Updated, + Content: "a realy good question!\r\n\r\nIt is the used as TESTSET for gitea2gitea repo migration function", + }, + { + IssueIndex: 4, + PosterID: -1, + PosterName: "Ghost", + PosterEmail: "", + Created: comments[1].Created, + Updated: comments[1].Updated, + Content: "Oh!", + }, + }, comments) + prs, isEnd, err := downloader.GetPullRequests(1, 50) + assert.NoError(t, err) + assert.True(t, isEnd) + assert.Len(t, prs, 6) + prs, isEnd, err = downloader.GetPullRequests(1, 3) + assert.NoError(t, err) + assert.False(t, isEnd) + assert.Len(t, prs, 3) + merged12 := time.Unix(1598982934, 0) + assertEqualPulls(t, &base.PullRequest{ + Number: 12, + PosterID: 689, + PosterName: "6543", + PosterEmail: "6543@noreply.gitea.io", + Title: "Dont Touch", + Content: "\r\nadd dont touch note", + Milestone: "V2 Finalize", + State: "closed", + IsLocked: false, + Created: time.Unix(1598982759, 0), + Updated: time.Unix(1598983027, 0), + Closed: &merged12, + Assignees: []string{"techknowlogick"}, + Labels: []*base.Label{}, + + Base: base.PullRequestBranch{ + CloneURL: "", + Ref: "master", + SHA: "827aa28a907853e5ddfa40c8f9bc52471a2685fd", + RepoName: "test_repo", + OwnerName: "gitea", + }, + Head: base.PullRequestBranch{ + CloneURL: "https://gitea.com/6543-forks/test_repo.git", + Ref: "refs/pull/12/head", + SHA: "", + RepoName: "test_repo", + OwnerName: "6543-forks", + }, + Merged: true, + MergedTime: &merged12, + MergeCommitSHA: "827aa28a907853e5ddfa40c8f9bc52471a2685fd", + PatchURL: "https://gitea.com/gitea/test_repo/pulls/12.patch", + }, prs[1]) } + +func assertEqualPulls(t *testing.T, pullExp, pullGet *base.PullRequest) { + assertEqualIssue(t, pull2issue(pullExp), pull2issue(pullGet)) + assert.EqualValues(t, 0, pullGet.OriginalNumber) + assert.EqualValues(t, pullExp.PatchURL, pullGet.PatchURL) + assert.EqualValues(t, pullExp.Merged, pullGet.Merged) + assert.EqualValues(t, pullExp.MergedTime.Unix(), pullGet.MergedTime.Unix()) + assert.EqualValues(t, pullExp.MergeCommitSHA, pullGet.MergeCommitSHA) + assert.EqualValues(t, pullExp.Base, pullGet.Base) + assert.EqualValues(t, pullExp.Head, pullGet.Head) +} + +func pull2issue(pull *base.PullRequest) *base.Issue { + return &base.Issue{ + Number: pull.Number, + PosterID: pull.PosterID, + PosterName: pull.PosterName, + PosterEmail: pull.PosterEmail, + Title: pull.Title, + Content: pull.Content, + Milestone: pull.Milestone, + State: pull.State, + IsLocked: pull.IsLocked, + Created: pull.Created, + Updated: pull.Updated, + Closed: pull.Closed, + Labels: pull.Labels, + Reactions: pull.Reactions, + Assignees: pull.Assignees, + } +} + +/* + ToDo: + GetReviews(pullRequestNumber int64) ([]*Review, error) +*/ From b46abd330ee7ac1b55f21bd29c560bfbfde30a85 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 2 Sep 2020 06:39:48 +0200 Subject: [PATCH 21/46] Workaround missing SHA --- modules/migrations/gitea_downloader.go | 6 +++++- modules/migrations/gitea_downloader_test.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index d1c44e9294b6..0ca469ebf7de 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -530,7 +530,11 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques headSHA = pr.Head.Sha headRef = pr.Head.Ref if headSHA == "" { - // ToDo: !!! ned get headSHA workaround + headCommit, err := g.client.GetSingleCommit(g.repoOwner, g.repoName, url.PathEscape(pr.Head.Ref)) + if err != nil { + return nil, false, fmt.Errorf("error while resolving git ref: %v", err) + } + headSHA = headCommit.SHA } } diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 40274e8f1e24..a1db81f08b0b 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -282,7 +282,7 @@ func TestGiteaDownloadRepo(t *testing.T) { Head: base.PullRequestBranch{ CloneURL: "https://gitea.com/6543-forks/test_repo.git", Ref: "refs/pull/12/head", - SHA: "", + SHA: "b6ab5d9ae000b579a5fff03f92c486da4ddf48b6", RepoName: "test_repo", OwnerName: "6543-forks", }, From 5738f74df6c7cd90cf05e7fbc4b5d24dddbabbc5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 2 Sep 2020 20:11:32 +0200 Subject: [PATCH 22/46] Adapt: Ensure that all migration requests are cancellable (714ab71ddc4260937b1480519d453d2dc4e77dd6) --- modules/migrations/base/downloader.go | 2 +- modules/migrations/gitea_downloader.go | 8 ++++---- modules/migrations/gitea_downloader_test.go | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/modules/migrations/base/downloader.go b/modules/migrations/base/downloader.go index fb07f181b1fb..5c47ed53052c 100644 --- a/modules/migrations/base/downloader.go +++ b/modules/migrations/base/downloader.go @@ -222,7 +222,7 @@ func (d *RetryDownloader) GetPullRequests(page, perPage int) ([]*PullRequest, bo } select { case <-d.ctx.Done(): - return nil, d.ctx.Err() + return nil, false, d.ctx.Err() case <-time.After(time.Second * time.Duration(d.RetryDelay)): } } diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 0ca469ebf7de..54ff32bf2a3b 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -35,7 +35,7 @@ type GiteaDownloaderFactory struct { } // New returns a Downloader related to this factory according MigrateOptions -func (f *GiteaDownloaderFactory) New(opts base.MigrateOptions) (base.Downloader, error) { +func (f *GiteaDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { u, err := url.Parse(opts.CloneAddr) if err != nil { return nil, err @@ -55,7 +55,7 @@ func (f *GiteaDownloaderFactory) New(opts base.MigrateOptions) (base.Downloader, log.Trace("Create gitea downloader. BaseURL: %s RepoName: %s", baseURL, repoNameSpace) - return NewGiteaDownloader(baseURL, repoPath, opts.AuthUsername, opts.AuthPassword, opts.AuthToken), nil + return NewGiteaDownloader(ctx, baseURL, repoPath, opts.AuthUsername, opts.AuthPassword, opts.AuthToken), nil } // GitServiceType returns the type of git service @@ -76,7 +76,7 @@ type GiteaDownloader struct { // NewGiteaDownloader creates a gitea Downloader via gitea API // Use either a username/password or personal token. token is preferred // Note: Public access only allows very basic access -func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *GiteaDownloader { +func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, password, token string) *GiteaDownloader { giteaClient := gitea_sdk.NewClient(baseURL, token) if token == "" { giteaClient.SetBasicAuth(username, password) @@ -102,7 +102,7 @@ func NewGiteaDownloader(baseURL, repoPath, username, password, token string) *Gi maxPerPage := 10 return &GiteaDownloader{ - ctx: context.Background(), + ctx: ctx, client: giteaClient, repoOwner: path[0], repoName: path[1], diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index a1db81f08b0b..561a2ec8f5af 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -5,6 +5,7 @@ package migrations import ( + "context" "fmt" "net/http" "os" @@ -52,7 +53,7 @@ func TestGiteaDownloadRepo(t *testing.T) { t.Skipf("Can't reach https://gitea.com, skipping %s", t.Name()) } - downloader := NewGiteaDownloader("https://gitea.com", "gitea/test_repo", "", "", giteaToken) + downloader := NewGiteaDownloader(context.Background(), "https://gitea.com", "gitea/test_repo", "", "", giteaToken) if downloader == nil { t.Fatal("NewGitlabDownloader is nil") } From b086983109096a97cff7f3923a92ffd278263d9c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Wed, 2 Sep 2020 20:24:34 +0200 Subject: [PATCH 23/46] LINT: fix misspells in test set --- modules/migrations/gitea_downloader_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 561a2ec8f5af..52a8435e6028 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -128,7 +128,7 @@ func TestGiteaDownloadRepo(t *testing.T) { Name: "Second Release", TagName: "v2-rc1", TargetCommitish: "master", - Body: "this repo has:\r\n* reactions\r\n* wiki\r\n* issues (open/closed)\r\n* pulls (open/closed/merged) (external/internal)\r\n* pull reviews\r\n* projects\r\n* milestones\r\n* lables\r\n* releases\r\n\r\nto test migration agains", + Body: "this repo has:\r\n* reactions\r\n* wiki\r\n* issues (open/closed)\r\n* pulls (open/closed/merged) (external/internal)\r\n* pull reviews\r\n* projects\r\n* milestones\r\n* labels\r\n* releases\r\n\r\nto test migration against", Draft: false, Prerelease: true, Created: time.Date(2020, 9, 1, 18, 2, 43, 0, time.UTC), @@ -224,7 +224,7 @@ func TestGiteaDownloadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, comments, 2) assert.EqualValues(t, 1598975370, comments[0].Created.Unix()) - assert.EqualValues(t, 1598975370, comments[0].Updated.Unix()) + assert.EqualValues(t, 1599070865, comments[0].Updated.Unix()) assert.EqualValues(t, 1598975393, comments[1].Created.Unix()) assert.EqualValues(t, 1598975393, comments[1].Updated.Unix()) assert.EqualValues(t, []*base.Comment{ @@ -235,7 +235,7 @@ func TestGiteaDownloadRepo(t *testing.T) { PosterEmail: "6543@noreply.gitea.io", Created: comments[0].Created, Updated: comments[0].Updated, - Content: "a realy good question!\r\n\r\nIt is the used as TESTSET for gitea2gitea repo migration function", + Content: "a really good question!\n\nIt is the used as TESTSET for gitea2gitea repo migration function", }, { IssueIndex: 4, @@ -268,7 +268,7 @@ func TestGiteaDownloadRepo(t *testing.T) { State: "closed", IsLocked: false, Created: time.Unix(1598982759, 0), - Updated: time.Unix(1598983027, 0), + Updated: time.Unix(1599023425, 0), Closed: &merged12, Assignees: []string{"techknowlogick"}, Labels: []*base.Label{}, From e4c8b7021a30a1874f6c623b8ac89e553f83995a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 3 Sep 2020 22:19:48 +0200 Subject: [PATCH 24/46] adapt ListMergeRequestAwardEmoji --- modules/migrations/gitlab.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/migrations/gitlab.go b/modules/migrations/gitlab.go index 3fcb1762d308..3474d076d53b 100644 --- a/modules/migrations/gitlab.go +++ b/modules/migrations/gitlab.go @@ -523,7 +523,7 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque for { awards, _, err := g.client.AwardEmoji.ListMergeRequestAwardEmoji(g.repoID, pr.IID, &gitlab.ListAwardEmojiOptions{Page: awardPage, PerPage: perPage}, gitlab.WithContext(g.ctx)) if err != nil { - return nil, fmt.Errorf("error while listing merge requests awards: %v", err) + return nil, false, fmt.Errorf("error while listing merge requests awards: %v", err) } if len(awards) < perPage { break From 0c460dc0499aab21fed176ebe268a32b97038f08 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 8 Sep 2020 11:55:00 +0200 Subject: [PATCH 25/46] update sdk --- go.mod | 2 +- go.sum | 4 +- modules/migrations/gitea_downloader.go | 2 +- vendor/code.gitea.io/sdk/gitea/admin_cron.go | 43 +++++++++++ vendor/code.gitea.io/sdk/gitea/client.go | 14 ++++ .../sdk/gitea/issue_milestone.go | 6 ++ vendor/code.gitea.io/sdk/gitea/org_team.go | 75 +++++++++++++++---- vendor/code.gitea.io/sdk/gitea/pull.go | 25 +++++++ vendor/code.gitea.io/sdk/gitea/pull_review.go | 12 +-- vendor/code.gitea.io/sdk/gitea/repo.go | 30 ++++++++ vendor/code.gitea.io/sdk/gitea/repo_branch.go | 40 ++++++++++ .../sdk/gitea/repo_collaborator.go | 33 +++++++- vendor/code.gitea.io/sdk/gitea/settings.go | 34 +++++++++ vendor/modules.txt | 2 +- 14 files changed, 289 insertions(+), 33 deletions(-) create mode 100644 vendor/code.gitea.io/sdk/gitea/admin_cron.go diff --git a/go.mod b/go.mod index 4dea6ff8b517..fb9544096270 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.14 require ( code.gitea.io/gitea-vet v0.2.1 - code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa + code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 diff --git a/go.sum b/go.sum index a5fd3e8a267e..cff59ebae731 100644 --- a/go.sum +++ b/go.sum @@ -15,8 +15,8 @@ cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2k cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa h1:DkcOvLx4GFIOgzOl6wKcocK3JIl0a9aV4u/MXUVS3SA= -code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= +code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 h1:9my9c8Ez4sOyKk00Jtp+wesG49S1Oe1RBqv8g3IqqXI= +code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 54ff32bf2a3b..9a989dea00d8 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -640,7 +640,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { for _, pr := range prl { - rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID, gitea_sdk.ListPullReviewsCommentsOptions{}) + rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID) if err != nil { return nil, err } diff --git a/vendor/code.gitea.io/sdk/gitea/admin_cron.go b/vendor/code.gitea.io/sdk/gitea/admin_cron.go new file mode 100644 index 000000000000..64984c06452e --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_cron.go @@ -0,0 +1,43 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "fmt" + "time" +) + +// CronTask represents a Cron task +type CronTask struct { + Name string `json:"name"` + Schedule string `json:"schedule"` + Next time.Time `json:"next"` + Prev time.Time `json:"prev"` + ExecTimes int64 `json:"exec_times"` +} + +// ListCronTaskOptions list options for ListCronTasks +type ListCronTaskOptions struct { + ListOptions +} + +// ListCronTasks list available cron tasks +func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + opt.setDefaults() + ct := make([]*CronTask, 0, opt.PageSize) + return ct, c.getParsedResponse("GET", fmt.Sprintf("/admin/cron?%s", opt.getURLQuery().Encode()), jsonHeader, nil, &ct) +} + +// RunCronTasks run a cron task +func (c *Client) RunCronTasks(task string) error { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return err + } + _, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil) + return err +} diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go index ccbe10e9a9aa..023f8f6606b8 100644 --- a/vendor/code.gitea.io/sdk/gitea/client.go +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -74,6 +74,20 @@ func (c *Client) SetSudo(sudo string) { c.sudo = sudo } +func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, error) { + req, err := http.NewRequest(method, c.url+path, body) + if err != nil { + return nil, err + } + resp, err := c.client.Do(req) + if err != nil { + return nil, err + } + + defer resp.Body.Close() + return ioutil.ReadAll(resp.Body) +} + func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) { req, err := http.NewRequest(method, c.url+"/api/v1"+path, body) if err != nil { diff --git a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go index 1270925c913c..acec831ad193 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -21,6 +21,8 @@ type Milestone struct { State StateType `json:"state"` OpenIssues int `json:"open_issues"` ClosedIssues int `json:"closed_issues"` + Created time.Time `json:"created_at"` + Updated *time.Time `json:"updated_at"` Closed *time.Time `json:"closed_at"` Deadline *time.Time `json:"due_on"` } @@ -30,6 +32,7 @@ type ListMilestoneOption struct { ListOptions // open, closed, all State StateType + Name string } // QueryEncode turns options into querystring argument @@ -38,6 +41,9 @@ func (opt *ListMilestoneOption) QueryEncode() string { if opt.State != "" { query.Add("state", string(opt.State)) } + if len(opt.Name) != 0 { + query.Add("name", opt.Name) + } return query.Encode() } diff --git a/vendor/code.gitea.io/sdk/gitea/org_team.go b/vendor/code.gitea.io/sdk/gitea/org_team.go index 4c786e3b8eb1..73e29be924c5 100644 --- a/vendor/code.gitea.io/sdk/gitea/org_team.go +++ b/vendor/code.gitea.io/sdk/gitea/org_team.go @@ -12,12 +12,13 @@ import ( // Team represents a team in an organization type Team struct { - ID int64 `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Organization *Organization `json:"organization"` - // enum: none,read,write,admin,owner - Permission string `json:"permission"` + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Organization *Organization `json:"organization"` + Permission AccessMode `json:"permission"` + CanCreateOrgRepo bool `json:"can_create_org_repo"` + IncludesAllRepositories bool `json:"includes_all_repositories"` // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] Units []string `json:"units"` } @@ -49,16 +50,39 @@ func (c *Client) GetTeam(id int64) (*Team, error) { // CreateTeamOption options for creating a team type CreateTeamOption struct { - Name string `json:"name"` - Description string `json:"description"` - // enum: read,write,admin - Permission string `json:"permission"` + Name string `json:"name"` + Description string `json:"description"` + Permission AccessMode `json:"permission"` + CanCreateOrgRepo bool `json:"can_create_org_repo"` + IncludesAllRepositories bool `json:"includes_all_repositories"` // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] Units []string `json:"units"` } +// Validate the CreateTeamOption struct +func (opt CreateTeamOption) Validate() error { + if opt.Permission == AccessModeOwner { + opt.Permission = AccessModeAdmin + } else if opt.Permission != AccessModeRead && opt.Permission != AccessModeWrite && opt.Permission != AccessModeAdmin { + return fmt.Errorf("permission mode invalid") + } + if len(opt.Name) == 0 { + return fmt.Errorf("name required") + } + if len(opt.Name) > 30 { + return fmt.Errorf("name to long") + } + if len(opt.Description) > 255 { + return fmt.Errorf("description to long") + } + return nil +} + // CreateTeam creates a team for an organization func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, error) { + if err := opt.Validate(); err != nil { + return nil, err + } body, err := json.Marshal(&opt) if err != nil { return nil, err @@ -69,16 +93,39 @@ func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, error) { // EditTeamOption options for editing a team type EditTeamOption struct { - Name string `json:"name"` - Description string `json:"description"` - // enum: read,write,admin - Permission string `json:"permission"` + Name string `json:"name"` + Description *string `json:"description"` + Permission AccessMode `json:"permission"` + CanCreateOrgRepo *bool `json:"can_create_org_repo"` + IncludesAllRepositories *bool `json:"includes_all_repositories"` // example: ["repo.code","repo.issues","repo.ext_issues","repo.wiki","repo.pulls","repo.releases","repo.ext_wiki"] Units []string `json:"units"` } +// Validate the EditTeamOption struct +func (opt EditTeamOption) Validate() error { + if opt.Permission == AccessModeOwner { + opt.Permission = AccessModeAdmin + } else if opt.Permission != AccessModeRead && opt.Permission != AccessModeWrite && opt.Permission != AccessModeAdmin { + return fmt.Errorf("permission mode invalid") + } + if len(opt.Name) == 0 { + return fmt.Errorf("name required") + } + if len(opt.Name) > 30 { + return fmt.Errorf("name to long") + } + if opt.Description != nil && len(*opt.Description) > 255 { + return fmt.Errorf("description to long") + } + return nil +} + // EditTeam edits a team of an organization func (c *Client) EditTeam(id int64, opt EditTeamOption) error { + if err := opt.Validate(); err != nil { + return err + } body, err := json.Marshal(&opt) if err != nil { return err diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go index d1659dc4c2c4..ff6f90f6d3a6 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull.go +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -220,3 +220,28 @@ func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, err return statusCode == 204, nil } + +// getPullRequestDiffOrPatch gets the patch or diff file as bytes for a PR +func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64) ([]byte, error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + r, err2 := c.GetRepo(owner, repo) + if err2 != nil { + return nil, err + } + if r.Private { + return nil, err + } + return c.getWebResponse("GET", fmt.Sprintf("/%s/%s/pulls/%d.%s", owner, repo, index, kind), nil) + } + return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d.%s", owner, repo, index, kind), nil, nil) +} + +// GetPullRequestPatch gets the .patch file as bytes for a PR +func (c *Client) GetPullRequestPatch(owner, repo string, index int64) ([]byte, error) { + return c.getPullRequestDiffOrPatch(owner, repo, "patch", index) +} + +// GetPullRequestDiff gets the .diff file as bytes for a PR +func (c *Client) GetPullRequestDiff(owner, repo string, index int64) ([]byte, error) { + return c.getPullRequestDiffOrPatch(owner, repo, "diff", index) +} diff --git a/vendor/code.gitea.io/sdk/gitea/pull_review.go b/vendor/code.gitea.io/sdk/gitea/pull_review.go index 8e5a5e84601a..169ac1a28aa9 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull_review.go +++ b/vendor/code.gitea.io/sdk/gitea/pull_review.go @@ -154,21 +154,13 @@ func (c *Client) GetPullReview(owner, repo string, index, id int64) (*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) { +func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]*PullReviewComment, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { return nil, err } - opt.setDefaults() - rcl := make([]*PullReviewComment, 0, opt.PageSize) - + rcl := make([]*PullReviewComment, 0, 4) 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) } diff --git a/vendor/code.gitea.io/sdk/gitea/repo.go b/vendor/code.gitea.io/sdk/gitea/repo.go index 0acc6ee34f01..3546ef26aa3a 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo.go +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -376,3 +376,33 @@ func (c *Client) MirrorSync(owner, repo string) error { _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil) return err } + +// GetRepoLanguages return language stats of a repo +func (c *Client) GetRepoLanguages(owner, repo string) (map[string]int64, error) { + langMap := make(map[string]int64) + + data, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/languages", owner, repo), jsonHeader, nil) + if err != nil { + return nil, err + } + if err = json.Unmarshal(data, &langMap); err != nil { + return nil, err + } + return langMap, nil +} + +// ArchiveType represent supported archive formats by gitea +type ArchiveType string + +const ( + // ZipArchive represent zip format + ZipArchive ArchiveType = ".zip" + // TarGZArchive represent tar.gz format + TarGZArchive ArchiveType = ".tar.gz" +) + +// GetArchive get an archive of a repository by git reference +// e.g.: ref -> master, 70b7c74b33, v1.2.1, ... +func (c *Client) GetArchive(owner, repo, ref string, ext ArchiveType) ([]byte, error) { + return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/archive/%s%s", owner, repo, url.PathEscape(ref), ext), nil, nil) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch.go b/vendor/code.gitea.io/sdk/gitea/repo_branch.go index 084a6ce7c3e0..a33f618d7083 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch.go @@ -6,6 +6,8 @@ package gitea import ( + "bytes" + "encoding/json" "fmt" "time" ) @@ -89,3 +91,41 @@ func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, error) { } return status == 204, nil } + +// CreateBranchOption options when creating a branch in a repository +type CreateBranchOption struct { + // Name of the branch to create + BranchName string `json:"new_branch_name"` + // Name of the old branch to create from (optional) + OldBranchName string `json:"old_branch_name"` +} + +// Validate the CreateBranchOption struct +func (opt CreateBranchOption) Validate() error { + if len(opt.BranchName) == 0 { + return fmt.Errorf("BranchName is empty") + } + if len(opt.BranchName) > 100 { + return fmt.Errorf("BranchName to long") + } + if len(opt.OldBranchName) > 100 { + return fmt.Errorf("OldBranchName to long") + } + return nil +} + +// CreateBranch creates a branch for a user's repository +func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + if err := opt.Validate(); err != nil { + return nil, err + } + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + branch := new(Branch) + return branch, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branches", owner, repo), jsonHeader, bytes.NewReader(body), branch) +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go index dbb72b268012..fb01986f93db 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -38,14 +38,39 @@ func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { // AddCollaboratorOption options when adding a user as a collaborator of a repository type AddCollaboratorOption struct { - Permission *string `json:"permission"` + Permission *AccessMode `json:"permission"` } +// AccessMode represent the grade of access you have to something +type AccessMode string + +const ( + // AccessModeNone no access + AccessModeNone AccessMode = "none" + // AccessModeRead read access + AccessModeRead AccessMode = "read" + // AccessModeWrite write access + AccessModeWrite AccessMode = "write" + // AccessModeAdmin admin access + AccessModeAdmin AccessMode = "admin" + // AccessModeOwner owner + AccessModeOwner AccessMode = "owner" +) + // Validate the AddCollaboratorOption struct func (opt AddCollaboratorOption) Validate() error { - if opt.Permission != nil && - *opt.Permission != "read" && *opt.Permission != "write" && *opt.Permission != "admin" { - return fmt.Errorf("permission mode invalid") + if opt.Permission != nil { + if *opt.Permission == AccessModeOwner { + *opt.Permission = AccessModeAdmin + return nil + } + if *opt.Permission == AccessModeNone { + opt.Permission = nil + return nil + } + if *opt.Permission != AccessModeRead && *opt.Permission != AccessModeWrite && *opt.Permission != AccessModeAdmin { + return fmt.Errorf("permission mode invalid") + } } return nil } diff --git a/vendor/code.gitea.io/sdk/gitea/settings.go b/vendor/code.gitea.io/sdk/gitea/settings.go index 42d2bd91e673..1ef1d93785c4 100644 --- a/vendor/code.gitea.io/sdk/gitea/settings.go +++ b/vendor/code.gitea.io/sdk/gitea/settings.go @@ -15,6 +15,22 @@ type GlobalRepoSettings struct { HTTPGitDisabled bool `json:"http_git_disabled"` } +// GlobalAPISettings contains global api settings exposed by it +type GlobalAPISettings struct { + MaxResponseItems int `json:"max_response_items"` + DefaultPagingNum int `json:"default_paging_num"` + DefaultGitTreesPerPage int `json:"default_git_trees_per_page"` + DefaultMaxBlobSize int64 `json:"default_max_blob_size"` +} + +// GlobalAttachmentSettings contains global Attachment settings exposed by API +type GlobalAttachmentSettings struct { + Enabled bool `json:"enabled"` + AllowedTypes string `json:"allowed_types"` + MaxSize int64 `json:"max_size"` + MaxFiles int `json:"max_files"` +} + // GetGlobalUISettings get global ui settings witch are exposed by API func (c *Client) GetGlobalUISettings() (settings *GlobalUISettings, err error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { @@ -32,3 +48,21 @@ func (c *Client) GetGlobalRepoSettings() (settings *GlobalRepoSettings, err erro conf := new(GlobalRepoSettings) return conf, c.getParsedResponse("GET", "/settings/repository", jsonHeader, nil, &conf) } + +// GetGlobalAPISettings get global api settings witch are exposed by it +func (c *Client) GetGlobalAPISettings() (settings *GlobalAPISettings, err error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + conf := new(GlobalAPISettings) + return conf, c.getParsedResponse("GET", "/settings/api", jsonHeader, nil, &conf) +} + +// GetGlobalAttachmentSettings get global repository settings witch are exposed by API +func (c *Client) GetGlobalAttachmentSettings() (settings *GlobalAttachmentSettings, err error) { + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + return nil, err + } + conf := new(GlobalAttachmentSettings) + return conf, c.getParsedResponse("GET", "/settings/attachment", jsonHeader, nil, &conf) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 8c458f3ea5a4..89ca65e27596 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,7 +4,7 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks -# code.gitea.io/sdk/gitea v0.12.1-0.20200730194618-9e280adb4daa +# code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 ## explicit code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0 From e868342dbc03b3961d66863b052e7e345509b44b Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 18:31:25 +0200 Subject: [PATCH 26/46] Return error when creating giteadownloader failed --- modules/migrations/gitea_downloader.go | 51 ++++----------------- modules/migrations/gitea_downloader_test.go | 7 ++- 2 files changed, 14 insertions(+), 44 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 9a989dea00d8..cc223bf9dca7 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -50,12 +50,12 @@ func (f *GiteaDownloaderFactory) New(ctx context.Context, opts base.MigrateOptio return nil, fmt.Errorf("invalid path") } - //ToDo handle gitea installed in subpath ... + //TODO handle gitea installed in subpath ... repoPath := repoNameSpace log.Trace("Create gitea downloader. BaseURL: %s RepoName: %s", baseURL, repoNameSpace) - return NewGiteaDownloader(ctx, baseURL, repoPath, opts.AuthUsername, opts.AuthPassword, opts.AuthToken), nil + return NewGiteaDownloader(ctx, baseURL, repoPath, opts.AuthUsername, opts.AuthPassword, opts.AuthToken) } // GitServiceType returns the type of git service @@ -76,7 +76,7 @@ type GiteaDownloader struct { // NewGiteaDownloader creates a gitea Downloader via gitea API // Use either a username/password or personal token. token is preferred // Note: Public access only allows very basic access -func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, password, token string) *GiteaDownloader { +func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, password, token string) (*GiteaDownloader, error) { giteaClient := gitea_sdk.NewClient(baseURL, token) if token == "" { giteaClient.SetBasicAuth(username, password) @@ -86,7 +86,7 @@ func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, passwo // because gitea v1.10.0 first got the needed pull & release endpoints if err := giteaClient.CheckServerVersionConstraint(">=1.10"); err != nil { log.Error(fmt.Sprintf("NewGiteaDownloader: %s", err.Error())) - return nil + return nil, err } path := strings.Split(repoPath, "/") @@ -98,7 +98,7 @@ func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, passwo // set small maxPerPage since we can only guess (default would be 50 but this can differ) // safest value would be 1 but this is really inefficient - // ToDo https://github.com/go-gitea/gitea/issues/12664 + // TODO https://github.com/go-gitea/gitea/issues/12664 maxPerPage := 10 return &GiteaDownloader{ @@ -108,7 +108,7 @@ func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, passwo repoName: path[1], pagination: paginationSupport, maxPerPage: maxPerPage, - } + }, nil } // SetContext set context @@ -139,18 +139,11 @@ func (g *GiteaDownloader) GetRepoInfo() (*base.Repository, error) { // GetTopics return gitea topics func (g *GiteaDownloader) GetTopics() ([]string, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } - return g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea_sdk.ListRepoTopicsOptions{}) } // GetMilestones returns milestones func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } var milestones = make([]*base.Milestone, 0, g.maxPerPage) for i := 1; ; i++ { @@ -173,7 +166,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { } for i := range ms { - // ToDo: expose this info + // TODO: expose this info // https://github.com/go-gitea/gitea/issues/12655 createdAT := time.Now() var updatedAT *time.Time @@ -209,10 +202,6 @@ func (g *GiteaDownloader) convertGiteaLabel(label *gitea_sdk.Label) *base.Label // GetLabels returns labels func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } - var labels = make([]*base.Label, 0, g.maxPerPage) for i := 1; ; i++ { @@ -273,11 +262,8 @@ func (g *GiteaDownloader) convertGiteaRelease(rel *gitea_sdk.Release) *base.Rele // GetReleases returns releases func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } - var releases = make([]*base.Release, 0, g.maxPerPage) + for i := 1; ; i++ { // make sure gitea can shutdown gracefully select { @@ -306,10 +292,6 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { // GetAsset returns an asset func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } - asset, err := g.client.GetReleaseAttachment(g.repoOwner, g.repoName, relID, id) if err != nil { return nil, err @@ -367,10 +349,6 @@ func (g *GiteaDownloader) getCommentReactions(commentID int64) ([]*base.Reaction // GetIssues returns issues according start and limit func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, error) { - if g == nil { - return nil, true, errors.New("error: GiteaDownloader is nil") - } - if perPage > g.maxPerPage { perPage = g.maxPerPage } @@ -434,10 +412,6 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err // GetComments returns comments according issueNumber func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } - var allComments = make([]*base.Comment, 0, g.maxPerPage) // for i := 1; ; i++ { @@ -474,7 +448,7 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { }) } - // ToDo enable pagination vor (gitea >= 1.13) when it got implemented + // TODO enable pagination vor (gitea >= 1.14) when it got implemented // if !g.pagination || len(comments) < g.maxPerPage { // break // } @@ -484,10 +458,6 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { // GetPullRequests returns pull requests according page and perPage func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullRequest, bool, error) { - if g == nil { - return nil, false, errors.New("error: GiteaDownloader is nil") - } - if perPage > g.maxPerPage { perPage = g.maxPerPage } @@ -612,9 +582,6 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques // GetReviews returns pull requests review func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { - if g == nil { - return nil, errors.New("error: GiteaDownloader is nil") - } if err := g.client.CheckServerVersionConstraint(">=1.12"); err != nil { log.Info("GiteaDownloader: instance to old, skip GetReviews") return nil, nil diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 52a8435e6028..2babf29e9110 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -53,17 +53,20 @@ func TestGiteaDownloadRepo(t *testing.T) { t.Skipf("Can't reach https://gitea.com, skipping %s", t.Name()) } - downloader := NewGiteaDownloader(context.Background(), "https://gitea.com", "gitea/test_repo", "", "", giteaToken) + downloader, err := NewGiteaDownloader(context.Background(), "https://gitea.com", "gitea/test_repo", "", "", giteaToken) if downloader == nil { t.Fatal("NewGitlabDownloader is nil") } + if !assert.NoError(t, err) { + t.Fatal("NewGitlabDownloader error occur") + } repo, err := downloader.GetRepoInfo() assert.NoError(t, err) assert.EqualValues(t, &base.Repository{ Name: "test_repo", Owner: "gitea", - IsPrivate: false, // ToDo: set test repo private + IsPrivate: false, // TODO: set test repo private Description: "Test repository for testing migration from gitea to gitea", CloneURL: "https://gitea.com/gitea/test_repo.git", OriginalURL: "https://gitea.com/gitea/test_repo", From d36d10da5398a2eba42ef40fe2d5074b23c3a429 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 18:35:34 +0200 Subject: [PATCH 27/46] update sdk --- go.mod | 4 +- go.sum | 4 +- vendor/code.gitea.io/sdk/gitea/admin_cron.go | 15 +-- vendor/code.gitea.io/sdk/gitea/admin_org.go | 13 +- vendor/code.gitea.io/sdk/gitea/admin_repo.go | 8 +- vendor/code.gitea.io/sdk/gitea/admin_user.go | 41 ++++--- vendor/code.gitea.io/sdk/gitea/attachment.go | 37 +++--- vendor/code.gitea.io/sdk/gitea/client.go | 56 +++++---- vendor/code.gitea.io/sdk/gitea/fork.go | 12 +- vendor/code.gitea.io/sdk/gitea/git_blob.go | 5 +- vendor/code.gitea.io/sdk/gitea/git_hook.go | 24 ++-- vendor/code.gitea.io/sdk/gitea/hook.go | 64 +++++----- vendor/code.gitea.io/sdk/gitea/issue.go | 37 +++--- .../code.gitea.io/sdk/gitea/issue_comment.go | 41 ++++--- vendor/code.gitea.io/sdk/gitea/issue_label.go | 66 +++++----- .../sdk/gitea/issue_milestone.go | 35 +++--- .../code.gitea.io/sdk/gitea/issue_reaction.go | 56 +++++---- .../sdk/gitea/issue_stopwatch.go | 23 ++-- .../sdk/gitea/issue_subscription.go | 54 ++++---- .../sdk/gitea/issue_tracked_time.go | 63 +++++++--- .../code.gitea.io/sdk/gitea/notifications.go | 76 ++++++------ vendor/code.gitea.io/sdk/gitea/oauth2.go | 50 ++++---- vendor/code.gitea.io/sdk/gitea/org.go | 40 +++--- vendor/code.gitea.io/sdk/gitea/org_member.go | 55 +++++---- vendor/code.gitea.io/sdk/gitea/org_team.go | 79 ++++++------ vendor/code.gitea.io/sdk/gitea/pull.go | 60 +++++---- vendor/code.gitea.io/sdk/gitea/pull_review.go | 53 ++++---- vendor/code.gitea.io/sdk/gitea/release.go | 36 +++--- vendor/code.gitea.io/sdk/gitea/repo.go | 106 +++++++--------- vendor/code.gitea.io/sdk/gitea/repo_branch.go | 35 +++--- .../sdk/gitea/repo_branch_protection.go | 42 ++++--- .../sdk/gitea/repo_collaborator.go | 31 ++--- vendor/code.gitea.io/sdk/gitea/repo_commit.go | 10 +- vendor/code.gitea.io/sdk/gitea/repo_file.go | 44 +++---- vendor/code.gitea.io/sdk/gitea/repo_key.go | 23 ++-- .../code.gitea.io/sdk/gitea/repo_migrate.go | 115 ++++++++++++++++++ vendor/code.gitea.io/sdk/gitea/repo_refs.go | 28 ++--- vendor/code.gitea.io/sdk/gitea/repo_tag.go | 5 +- vendor/code.gitea.io/sdk/gitea/repo_topics.go | 28 ++--- .../code.gitea.io/sdk/gitea/repo_transfer.go | 9 +- vendor/code.gitea.io/sdk/gitea/repo_tree.go | 5 +- vendor/code.gitea.io/sdk/gitea/repo_watch.go | 42 ++++--- vendor/code.gitea.io/sdk/gitea/settings.go | 28 +++-- vendor/code.gitea.io/sdk/gitea/status.go | 17 +-- vendor/code.gitea.io/sdk/gitea/user.go | 12 +- vendor/code.gitea.io/sdk/gitea/user_app.go | 42 +++++-- vendor/code.gitea.io/sdk/gitea/user_email.go | 20 +-- vendor/code.gitea.io/sdk/gitea/user_follow.go | 44 ++++--- vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 28 +++-- vendor/code.gitea.io/sdk/gitea/user_key.go | 28 +++-- vendor/code.gitea.io/sdk/gitea/user_search.go | 8 +- vendor/code.gitea.io/sdk/gitea/version.go | 7 +- vendor/modules.txt | 4 +- 53 files changed, 1071 insertions(+), 797 deletions(-) create mode 100644 vendor/code.gitea.io/sdk/gitea/repo_migrate.go diff --git a/go.mod b/go.mod index a1ba70f69412..b8d7a1550717 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.14 require ( code.gitea.io/gitea-vet v0.2.1 - code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 + code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 @@ -51,7 +51,7 @@ require ( github.com/google/uuid v1.1.1 github.com/gorilla/context v1.1.1 github.com/hashicorp/go-retryablehttp v0.6.7 // indirect - github.com/hashicorp/go-version v1.2.0 + github.com/hashicorp/go-version v1.2.1 github.com/huandu/xstrings v1.3.0 github.com/issue9/assert v1.3.2 // indirect github.com/issue9/identicon v1.0.1 diff --git a/go.sum b/go.sum index 247bcd86d7e9..927424ca00f2 100644 --- a/go.sum +++ b/go.sum @@ -15,8 +15,8 @@ cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2k cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 h1:9my9c8Ez4sOyKk00Jtp+wesG49S1Oe1RBqv8g3IqqXI= -code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= +code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd h1:ELLGt+i91Ffpj/RKEfzN7TwO51KH42JhP7ZbHamWAz4= +code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= diff --git a/vendor/code.gitea.io/sdk/gitea/admin_cron.go b/vendor/code.gitea.io/sdk/gitea/admin_cron.go index 64984c06452e..72f77e55ee9b 100644 --- a/vendor/code.gitea.io/sdk/gitea/admin_cron.go +++ b/vendor/code.gitea.io/sdk/gitea/admin_cron.go @@ -24,20 +24,21 @@ type ListCronTaskOptions struct { } // ListCronTasks list available cron tasks -func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, error) { +func (c *Client) ListCronTasks(opt ListCronTaskOptions) ([]*CronTask, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } opt.setDefaults() ct := make([]*CronTask, 0, opt.PageSize) - return ct, c.getParsedResponse("GET", fmt.Sprintf("/admin/cron?%s", opt.getURLQuery().Encode()), jsonHeader, nil, &ct) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/cron?%s", opt.getURLQuery().Encode()), jsonHeader, nil, &ct) + return ct, resp, err } // RunCronTasks run a cron task -func (c *Client) RunCronTasks(task string) error { +func (c *Client) RunCronTasks(task string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return err + return nil, err } - _, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil) - return err + _, resp, err := c.getResponse("POST", fmt.Sprintf("/admin/cron/%s", task), jsonHeader, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/admin_org.go b/vendor/code.gitea.io/sdk/gitea/admin_org.go index 8b0bac18f35e..e572680fc0a7 100644 --- a/vendor/code.gitea.io/sdk/gitea/admin_org.go +++ b/vendor/code.gitea.io/sdk/gitea/admin_org.go @@ -17,19 +17,20 @@ type AdminListOrgsOptions struct { } // AdminListOrgs lists all orgs -func (c *Client) AdminListOrgs(opt AdminListOrgsOptions) ([]*Organization, error) { +func (c *Client) AdminListOrgs(opt AdminListOrgsOptions) ([]*Organization, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs) + return orgs, resp, err } // AdminCreateOrg create an organization -func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) { +func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } org := new(Organization) - return org, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user), - jsonHeader, bytes.NewReader(body), org) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user), jsonHeader, bytes.NewReader(body), org) + return org, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/admin_repo.go b/vendor/code.gitea.io/sdk/gitea/admin_repo.go index cf565ffa38b1..cbd97881793a 100644 --- a/vendor/code.gitea.io/sdk/gitea/admin_repo.go +++ b/vendor/code.gitea.io/sdk/gitea/admin_repo.go @@ -11,12 +11,12 @@ import ( ) // AdminCreateRepo create a repo -func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, error) { +func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } repo := new(Repository) - return repo, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user), - jsonHeader, bytes.NewReader(body), repo) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user), jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/admin_user.go b/vendor/code.gitea.io/sdk/gitea/admin_user.go index 13a877653e2a..5f4917896e49 100644 --- a/vendor/code.gitea.io/sdk/gitea/admin_user.go +++ b/vendor/code.gitea.io/sdk/gitea/admin_user.go @@ -17,10 +17,11 @@ type AdminListUsersOptions struct { } // AdminListUsers lists all users -func (c *Client) AdminListUsers(opt AdminListUsersOptions) ([]*User, error) { +func (c *Client) AdminListUsers(opt AdminListUsersOptions) ([]*User, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/admin/users?%s", opt.getURLQuery().Encode()), nil, nil, &users) + return users, resp, err } // CreateUserOption create user options @@ -47,16 +48,17 @@ func (opt CreateUserOption) Validate() error { } // AdminCreateUser create a user -func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, error) { +func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } user := new(User) - return user, c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user) + resp, err := c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user) + return user, resp, err } // EditUserOption edit user options @@ -79,33 +81,34 @@ type EditUserOption struct { } // AdminEditUser modify user informations -func (c *Client) AdminEditUser(user string, opt EditUserOption) error { +func (c *Client) AdminEditUser(user string, opt EditUserOption) (*Response, error) { body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body)) + return resp, err } // AdminDeleteUser delete one user according name -func (c *Client) AdminDeleteUser(user string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil) - return err +func (c *Client) AdminDeleteUser(user string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil) + return resp, err } // AdminCreateUserPublicKey adds a public key for the user -func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, error) { +func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } key := new(PublicKey) - return key, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key) + return key, resp, err } // AdminDeleteUserPublicKey deletes a user's public key -func (c *Client) AdminDeleteUserPublicKey(user string, keyID int) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s/keys/%d", user, keyID), nil, nil) - return err +func (c *Client) AdminDeleteUserPublicKey(user string, keyID int) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s/keys/%d", user, keyID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/attachment.go b/vendor/code.gitea.io/sdk/gitea/attachment.go index a13787be86ab..6f67ae3de5a1 100644 --- a/vendor/code.gitea.io/sdk/gitea/attachment.go +++ b/vendor/code.gitea.io/sdk/gitea/attachment.go @@ -30,47 +30,47 @@ type ListReleaseAttachmentsOptions struct { } // ListReleaseAttachments list release's attachments -func (c *Client) ListReleaseAttachments(user, repo string, release int64, opt ListReleaseAttachmentsOptions) ([]*Attachment, error) { +func (c *Client) ListReleaseAttachments(user, repo string, release int64, opt ListReleaseAttachmentsOptions) ([]*Attachment, *Response, error) { opt.setDefaults() attachments := make([]*Attachment, 0, opt.PageSize) - err := c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/releases/%d/assets?%s", user, repo, release, opt.getURLQuery().Encode()), nil, nil, &attachments) - return attachments, err + return attachments, resp, err } // GetReleaseAttachment returns the requested attachment -func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, error) { +func (c *Client) GetReleaseAttachment(user, repo string, release int64, id int64) (*Attachment, *Response, error) { a := new(Attachment) - err := c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil, &a) - return a, err + return a, resp, err } // CreateReleaseAttachment creates an attachment for the given release -func (c *Client) CreateReleaseAttachment(user, repo string, release int64, file io.Reader, filename string) (*Attachment, error) { +func (c *Client) CreateReleaseAttachment(user, repo string, release int64, file io.Reader, filename string) (*Attachment, *Response, error) { // Write file to body body := new(bytes.Buffer) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) if err != nil { - return nil, err + return nil, nil, err } if _, err = io.Copy(part, file); err != nil { - return nil, err + return nil, nil, err } if err = writer.Close(); err != nil { - return nil, err + return nil, nil, err } // Send request attachment := new(Attachment) - err = c.getParsedResponse("POST", + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), http.Header{"Content-Type": {writer.FormDataContentType()}}, body, &attachment) - return attachment, err + return attachment, resp, err } // EditAttachmentOptions options for editing attachments @@ -79,17 +79,18 @@ type EditAttachmentOptions struct { } // EditReleaseAttachment updates the given attachment with the given options -func (c *Client) EditReleaseAttachment(user, repo string, release int64, attachment int64, form EditAttachmentOptions) (*Attachment, error) { +func (c *Client) EditReleaseAttachment(user, repo string, release int64, attachment int64, form EditAttachmentOptions) (*Attachment, *Response, error) { body, err := json.Marshal(&form) if err != nil { - return nil, err + return nil, nil, err } attach := new(Attachment) - return attach, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, attachment), jsonHeader, bytes.NewReader(body), attach) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, attachment), jsonHeader, bytes.NewReader(body), attach) + return attach, resp, err } // DeleteReleaseAttachment deletes the given attachment including the uploaded file -func (c *Client) DeleteReleaseAttachment(user, repo string, release int64, id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil) - return err +func (c *Client) DeleteReleaseAttachment(user, repo string, release int64, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d/assets/%d", user, repo, release, id), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go index 023f8f6606b8..7cadebd9dd33 100644 --- a/vendor/code.gitea.io/sdk/gitea/client.go +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -38,6 +38,11 @@ type Client struct { versionLock sync.RWMutex } +// Response represents the gitea response +type Response struct { + *http.Response +} + // NewClient initializes and returns a API client. func NewClient(url, token string) *Client { return &Client{ @@ -74,21 +79,22 @@ func (c *Client) SetSudo(sudo string) { c.sudo = sudo } -func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, error) { +func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) { req, err := http.NewRequest(method, c.url+path, body) if err != nil { - return nil, err + return nil, nil, err } resp, err := c.client.Do(req) if err != nil { - return nil, err + return nil, nil, err } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + data, err := ioutil.ReadAll(resp.Body) + return data, &Response{resp}, nil } -func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) { +func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) { req, err := http.NewRequest(method, c.url+"/api/v1"+path, body) if err != nil { return nil, err @@ -109,30 +115,34 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read req.Header[k] = v } - return c.client.Do(req) + resp, err := c.client.Do(req) + if err != nil { + return nil, err + } + return &Response{resp}, nil } -func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) { +func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, *Response, error) { resp, err := c.doRequest(method, path, header, body) if err != nil { - return nil, err + return nil, nil, err } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { - return nil, err + return nil, resp, err } switch resp.StatusCode { case 403: - return nil, errors.New("403 Forbidden") + return data, resp, errors.New("403 Forbidden") case 404: - return nil, errors.New("404 Not Found") + return data, resp, errors.New("404 Not Found") case 409: - return nil, errors.New("409 Conflict") + return data, resp, errors.New("409 Conflict") case 422: - return nil, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) + return data, resp, fmt.Errorf("422 Unprocessable Entity: %s", string(data)) } if resp.StatusCode/100 != 2 { @@ -140,28 +150,28 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re if err = json.Unmarshal(data, &errMap); err != nil { // when the JSON can't be parsed, data was probably empty or a plain string, // so we try to return a helpful error anyway - return nil, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data)) + return data, resp, fmt.Errorf("Unknown API Error: %d\nRequest: '%s' with '%s' method '%s' header and '%s' body", resp.StatusCode, path, method, header, string(data)) } - return nil, errors.New(errMap["message"].(string)) + return data, resp, errors.New(errMap["message"].(string)) } - return data, nil + return data, resp, nil } -func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error { - data, err := c.getResponse(method, path, header, body) +func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) (*Response, error) { + data, resp, err := c.getResponse(method, path, header, body) if err != nil { - return err + return nil, err } - return json.Unmarshal(data, obj) + return resp, json.Unmarshal(data, obj) } -func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, error) { +func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, *Response, error) { resp, err := c.doRequest(method, path, header, body) if err != nil { - return -1, err + return -1, resp, err } defer resp.Body.Close() - return resp.StatusCode, nil + return resp.StatusCode, resp, nil } diff --git a/vendor/code.gitea.io/sdk/gitea/fork.go b/vendor/code.gitea.io/sdk/gitea/fork.go index fe197462c10c..a5197125da67 100644 --- a/vendor/code.gitea.io/sdk/gitea/fork.go +++ b/vendor/code.gitea.io/sdk/gitea/fork.go @@ -16,12 +16,13 @@ type ListForksOptions struct { } // ListForks list a repository's forks -func (c *Client) ListForks(user string, repo string, opt ListForksOptions) ([]*Repository, error) { +func (c *Client) ListForks(user string, repo string, opt ListForksOptions) ([]*Repository, *Response, error) { opt.setDefaults() forks := make([]*Repository, opt.PageSize) - return forks, c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/forks?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &forks) + return forks, resp, err } // CreateForkOption options for creating a fork @@ -31,11 +32,12 @@ type CreateForkOption struct { } // CreateFork create a fork of a repository -func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Repository, error) { +func (c *Client) CreateFork(user, repo string, form CreateForkOption) (*Repository, *Response, error) { body, err := json.Marshal(form) if err != nil { - return nil, err + return nil, nil, err } fork := new(Repository) - return fork, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/forks", user, repo), jsonHeader, bytes.NewReader(body), &fork) + return fork, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/git_blob.go b/vendor/code.gitea.io/sdk/gitea/git_blob.go index 2843bc35833f..262fd92dfd2b 100644 --- a/vendor/code.gitea.io/sdk/gitea/git_blob.go +++ b/vendor/code.gitea.io/sdk/gitea/git_blob.go @@ -18,7 +18,8 @@ type GitBlobResponse struct { } // GetBlob get the blob of a repository file -func (c *Client) GetBlob(user, repo, sha string) (*GitBlobResponse, error) { +func (c *Client) GetBlob(user, repo, sha string) (*GitBlobResponse, *Response, error) { blob := new(GitBlobResponse) - return blob, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/blobs/%s", user, repo, sha), nil, nil, blob) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/blobs/%s", user, repo, sha), nil, nil, blob) + return blob, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/git_hook.go b/vendor/code.gitea.io/sdk/gitea/git_hook.go index 1162d091167b..520ce538ed9d 100644 --- a/vendor/code.gitea.io/sdk/gitea/git_hook.go +++ b/vendor/code.gitea.io/sdk/gitea/git_hook.go @@ -23,16 +23,18 @@ type ListRepoGitHooksOptions struct { } // ListRepoGitHooks list all the Git hooks of one repository -func (c *Client) ListRepoGitHooks(user, repo string, opt ListRepoGitHooksOptions) ([]*GitHook, error) { +func (c *Client) ListRepoGitHooks(user, repo string, opt ListRepoGitHooksOptions) ([]*GitHook, *Response, error) { opt.setDefaults() hooks := make([]*GitHook, 0, opt.PageSize) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) + return hooks, resp, err } // GetRepoGitHook get a Git hook of a repository -func (c *Client) GetRepoGitHook(user, repo, id string) (*GitHook, error) { +func (c *Client) GetRepoGitHook(user, repo, id string) (*GitHook, *Response, error) { h := new(GitHook) - return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil, h) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil, h) + return h, resp, err } // EditGitHookOption options when modifying one Git hook @@ -41,17 +43,17 @@ type EditGitHookOption struct { } // EditRepoGitHook modify one Git hook of a repository -func (c *Client) EditRepoGitHook(user, repo, id string, opt EditGitHookOption) error { +func (c *Client) EditRepoGitHook(user, repo, id string, opt EditGitHookOption) (*Response, error) { body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), jsonHeader, bytes.NewReader(body)) + return resp, err } // DeleteRepoGitHook delete one Git hook from a repository -func (c *Client) DeleteRepoGitHook(user, repo, id string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil) - return err +func (c *Client) DeleteRepoGitHook(user, repo, id string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/git/%s", user, repo, id), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go index 1ca1a3b0eb7a..3a6be65ef766 100644 --- a/vendor/code.gitea.io/sdk/gitea/hook.go +++ b/vendor/code.gitea.io/sdk/gitea/hook.go @@ -30,29 +30,33 @@ type ListHooksOptions struct { } // ListOrgHooks list all the hooks of one organization -func (c *Client) ListOrgHooks(org string, opt ListHooksOptions) ([]*Hook, error) { +func (c *Client) ListOrgHooks(org string, opt ListHooksOptions) ([]*Hook, *Response, error) { opt.setDefaults() hooks := make([]*Hook, 0, opt.PageSize) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks?%s", org, opt.getURLQuery().Encode()), nil, nil, &hooks) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks?%s", org, opt.getURLQuery().Encode()), nil, nil, &hooks) + return hooks, resp, err } // ListRepoHooks list all the hooks of one repository -func (c *Client) ListRepoHooks(user, repo string, opt ListHooksOptions) ([]*Hook, error) { +func (c *Client) ListRepoHooks(user, repo string, opt ListHooksOptions) ([]*Hook, *Response, error) { opt.setDefaults() hooks := make([]*Hook, 0, opt.PageSize) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &hooks) + return hooks, resp, err } // GetOrgHook get a hook of an organization -func (c *Client) GetOrgHook(org string, id int64) (*Hook, error) { +func (c *Client) GetOrgHook(org string, id int64) (*Hook, *Response, error) { h := new(Hook) - return h, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil, h) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil, h) + return h, resp, err } // GetRepoHook get a hook of a repository -func (c *Client) GetRepoHook(user, repo string, id int64) (*Hook, error) { +func (c *Client) GetRepoHook(user, repo string, id int64) (*Hook, *Response, error) { h := new(Hook) - return h, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil, h) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil, h) + return h, resp, err } // CreateHookOption options when create a hook @@ -73,26 +77,28 @@ func (opt CreateHookOption) Validate() error { } // CreateOrgHook create one hook for an organization, with options -func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, error) { +func (c *Client) CreateOrgHook(org string, opt CreateHookOption) (*Hook, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } h := new(Hook) - return h, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/hooks", org), jsonHeader, bytes.NewReader(body), h) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/hooks", org), jsonHeader, bytes.NewReader(body), h) + return h, resp, err } // CreateRepoHook create one hook for a repository, with options -func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, error) { +func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } h := new(Hook) - return h, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h) + return h, resp, err } // EditHookOption options when modify one hook @@ -104,33 +110,33 @@ type EditHookOption struct { } // EditOrgHook modify one hook of an organization, with hook id and options -func (c *Client) EditOrgHook(org string, id int64, opt EditHookOption) error { +func (c *Client) EditOrgHook(org string, id int64, opt EditHookOption) (*Response, error) { body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), jsonHeader, bytes.NewReader(body)) + return resp, err } // EditRepoHook modify one hook of a repository, with hook id and options -func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) error { +func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) (*Response, error) { body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body)) + return resp, err } // DeleteOrgHook delete one hook from an organization, with hook id -func (c *Client) DeleteOrgHook(org string, id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil) - return err +func (c *Client) DeleteOrgHook(org string, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/hooks/%d", org, id), nil, nil) + return resp, err } // DeleteRepoHook delete one hook from a repository, with hook id -func (c *Client) DeleteRepoHook(user, repo string, id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil) - return err +func (c *Client) DeleteRepoHook(user, repo string, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue.go b/vendor/code.gitea.io/sdk/gitea/issue.go index dd591f3c1e76..1b09b3f79628 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue.go +++ b/vendor/code.gitea.io/sdk/gitea/issue.go @@ -114,13 +114,13 @@ func (opt *ListIssueOption) QueryEncode() string { } // ListIssues returns all issues assigned the authenticated user -func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { +func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, *Response, error) { opt.setDefaults() issues := make([]*Issue, 0, opt.PageSize) link, _ := url.Parse("/repos/issues/search") link.RawQuery = opt.QueryEncode() - err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { for i := 0; i < len(issues); i++ { if issues[i].Repository != nil { @@ -128,17 +128,17 @@ func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { } } } - return issues, err + return issues, resp, err } // ListRepoIssues returns all issues for a given repository -func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) { +func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, *Response, error) { opt.setDefaults() issues := make([]*Issue, 0, opt.PageSize) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/issues", owner, repo)) link.RawQuery = opt.QueryEncode() - err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &issues) if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { for i := 0; i < len(issues); i++ { if issues[i].Repository != nil { @@ -146,17 +146,17 @@ func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Iss } } } - return issues, err + return issues, resp, err } // GetIssue returns a single issue for a given repository -func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { +func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, *Response, error) { issue := new(Issue) - err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil && issue.Repository != nil { issue.Repository.Owner = strings.Split(issue.Repository.FullName, "/")[0] } - return issue, err + return issue, resp, err } // CreateIssueOption options to create one issue @@ -183,17 +183,18 @@ func (opt CreateIssueOption) Validate() error { } // CreateIssue create a new issue for a given repository -func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) { +func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } issue := new(Issue) - return issue, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo), + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo), jsonHeader, bytes.NewReader(body), issue) + return issue, resp, err } // EditIssueOption options for editing an issue @@ -216,15 +217,17 @@ func (opt EditIssueOption) Validate() error { } // EditIssue modify an existing issue for a given repository -func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, error) { +func (c *Client) EditIssue(owner, repo string, index int64, opt EditIssueOption) (*Issue, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } issue := new(Issue) - return issue, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), + resp, err := c.getParsedResponse("PATCH", + fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), jsonHeader, bytes.NewReader(body), issue) + return issue, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_comment.go b/vendor/code.gitea.io/sdk/gitea/issue_comment.go index 1c0a1de4fc1a..50b3532645bb 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_comment.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_comment.go @@ -46,30 +46,33 @@ func (opt *ListIssueCommentOptions) QueryEncode() string { } // ListIssueComments list comments on an issue. -func (c *Client) ListIssueComments(owner, repo string, index int64, opt ListIssueCommentOptions) ([]*Comment, error) { +func (c *Client) ListIssueComments(owner, repo string, index int64, opt ListIssueCommentOptions) ([]*Comment, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &comments) + return comments, resp, err } // ListRepoIssueComments list comments for a given repo. -func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentOptions) ([]*Comment, error) { +func (c *Client) ListRepoIssueComments(owner, repo string, opt ListIssueCommentOptions) ([]*Comment, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &comments) + return comments, resp, err } // GetIssueComment get a comment for a given repo by id. -func (c *Client) GetIssueComment(owner, repo string, id int64) (*Comment, error) { +func (c *Client) GetIssueComment(owner, repo string, id int64) (*Comment, *Response, error) { comment := new(Comment) if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return comment, err + return comment, nil, err } - return comment, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, id), nil, nil, &comment) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, id), nil, nil, &comment) + return comment, resp, err } // CreateIssueCommentOption options for creating a comment on an issue @@ -86,16 +89,17 @@ func (opt CreateIssueCommentOption) Validate() error { } // CreateIssueComment create comment on an issue. -func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, error) { +func (c *Client) CreateIssueComment(owner, repo string, index int64, opt CreateIssueCommentOption) (*Comment, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } comment := new(Comment) - return comment, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), jsonHeader, bytes.NewReader(body), comment) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), jsonHeader, bytes.NewReader(body), comment) + return comment, resp, err } // EditIssueCommentOption options for editing a comment @@ -112,20 +116,21 @@ func (opt EditIssueCommentOption) Validate() error { } // EditIssueComment edits an issue comment. -func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, error) { +func (c *Client) EditIssueComment(owner, repo string, commentID int64, opt EditIssueCommentOption) (*Comment, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } comment := new(Comment) - return comment, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), jsonHeader, bytes.NewReader(body), comment) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), jsonHeader, bytes.NewReader(body), comment) + return comment, resp, err } // DeleteIssueComment deletes an issue comment. -func (c *Client) DeleteIssueComment(owner, repo string, commentID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), nil, nil) - return err +func (c *Client) DeleteIssueComment(owner, repo string, commentID int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d", owner, repo, commentID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_label.go b/vendor/code.gitea.io/sdk/gitea/issue_label.go index d067d70a5f93..1eb3c744f755 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_label.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_label.go @@ -28,16 +28,18 @@ type ListLabelsOptions struct { } // ListRepoLabels list labels of one repository -func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*Label, error) { +func (c *Client) ListRepoLabels(owner, repo string, opt ListLabelsOptions) ([]*Label, *Response, error) { opt.setDefaults() labels := make([]*Label, 0, opt.PageSize) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels?%s", owner, repo, opt.getURLQuery().Encode()), nil, nil, &labels) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels?%s", owner, repo, opt.getURLQuery().Encode()), nil, nil, &labels) + return labels, resp, err } // GetRepoLabel get one label of repository by repo it -func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, error) { +func (c *Client) GetRepoLabel(owner, repo string, id int64) (*Label, *Response, error) { label := new(Label) - return label, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil, label) + return label, resp, err } // CreateLabelOption options for creating a label @@ -64,9 +66,9 @@ func (opt CreateLabelOption) Validate() error { } // CreateLabel create one label of repository -func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { +func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } if len(opt.Color) == 6 { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { @@ -75,11 +77,13 @@ func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } label := new(Label) - return label, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/labels", owner, repo), jsonHeader, bytes.NewReader(body), label) + return label, resp, err } // EditLabelOption options for editing a label @@ -109,28 +113,30 @@ func (opt EditLabelOption) Validate() error { } // EditLabel modify one label with options -func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, error) { +func (c *Client) EditLabel(owner, repo string, id int64, opt EditLabelOption) (*Label, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } label := new(Label) - return label, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), label) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), label) + return label, resp, err } // DeleteLabel delete one label of repository by id -func (c *Client) DeleteLabel(owner, repo string, id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil) - return err +func (c *Client) DeleteLabel(owner, repo string, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/labels/%d", owner, repo, id), nil, nil) + return resp, err } // GetIssueLabels get labels of one issue via issue id -func (c *Client) GetIssueLabels(owner, repo string, index int64, opts ListLabelsOptions) ([]*Label, error) { +func (c *Client) GetIssueLabels(owner, repo string, index int64, opts ListLabelsOptions) ([]*Label, *Response, error) { labels := make([]*Label, 0, 5) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels?%s", owner, repo, index, opts.getURLQuery().Encode()), nil, nil, &labels) + return labels, resp, err } // IssueLabelsOption a collection of labels @@ -140,34 +146,36 @@ type IssueLabelsOption struct { } // AddIssueLabels add one or more labels to one issue -func (c *Client) AddIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { +func (c *Client) AddIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } var labels []*Label - return labels, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) + return labels, resp, err } // ReplaceIssueLabels replace old labels of issue with new labels -func (c *Client) ReplaceIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, error) { +func (c *Client) ReplaceIssueLabels(owner, repo string, index int64, opt IssueLabelsOption) ([]*Label, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } var labels []*Label - return labels, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) + resp, err := c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), jsonHeader, bytes.NewReader(body), &labels) + return labels, resp, err } // DeleteIssueLabel delete one label of one issue by issue id and label id // TODO: maybe we need delete by label name and issue id -func (c *Client) DeleteIssueLabel(owner, repo string, index, label int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, index, label), nil, nil) - return err +func (c *Client) DeleteIssueLabel(owner, repo string, index, label int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, index, label), nil, nil) + return resp, err } // ClearIssueLabels delete all the labels of one issue. -func (c *Client) ClearIssueLabels(owner, repo string, index int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil) - return err +func (c *Client) ClearIssueLabels(owner, repo string, index int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go index acec831ad193..11719f22ec74 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -48,19 +48,21 @@ func (opt *ListMilestoneOption) QueryEncode() string { } // ListRepoMilestones list all the milestones of one repository -func (c *Client) ListRepoMilestones(owner, repo string, opt ListMilestoneOption) ([]*Milestone, error) { +func (c *Client) ListRepoMilestones(owner, repo string, opt ListMilestoneOption) ([]*Milestone, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &milestones) + return milestones, resp, err } // GetMilestone get one milestone by repo name and milestone id -func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, error) { +func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, *Response, error) { milestone := new(Milestone) - return milestone, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil, milestone) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil, milestone) + return milestone, resp, err } // CreateMilestoneOption options for creating a milestone @@ -80,16 +82,16 @@ func (opt CreateMilestoneOption) Validate() error { } // CreateMilestone create one milestone with options -func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, error) { +func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) (*Milestone, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } milestone := new(Milestone) - err = c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) // make creating closed milestones need gitea >= v1.13.0 // this make it backwards compatible @@ -100,7 +102,7 @@ func (c *Client) CreateMilestone(owner, repo string, opt CreateMilestoneOption) }) } - return milestone, err + return milestone, resp, err } // EditMilestoneOption options for editing a milestone @@ -120,20 +122,21 @@ func (opt EditMilestoneOption) Validate() error { } // EditMilestone modify milestone with options -func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, error) { +func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOption) (*Milestone, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } milestone := new(Milestone) - return milestone, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), milestone) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), jsonHeader, bytes.NewReader(body), milestone) + return milestone, resp, err } // DeleteMilestone delete one milestone by milestone id -func (c *Client) DeleteMilestone(owner, repo string, id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil) - return err +func (c *Client) DeleteMilestone(owner, repo string, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_reaction.go b/vendor/code.gitea.io/sdk/gitea/issue_reaction.go index fb7d6d6cf708..a70209a0e3c4 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_reaction.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_reaction.go @@ -19,21 +19,23 @@ type Reaction struct { } // GetIssueReactions get a list reactions of an issue -func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction, error) { +func (c *Client) GetIssueReactions(owner, repo string, index int64) ([]*Reaction, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return nil, err + return nil, nil, err } reactions := make([]*Reaction, 0, 10) - return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), nil, nil, &reactions) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), nil, nil, &reactions) + return reactions, resp, err } // GetIssueCommentReactions get a list of reactions from a comment of an issue -func (c *Client) GetIssueCommentReactions(owner, repo string, commentID int64) ([]*Reaction, error) { +func (c *Client) GetIssueCommentReactions(owner, repo string, commentID int64) ([]*Reaction, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return nil, err + return nil, nil, err } reactions := make([]*Reaction, 0, 10) - return reactions, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), nil, nil, &reactions) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), nil, nil, &reactions) + return reactions, resp, err } // editReactionOption contain the reaction type @@ -42,57 +44,61 @@ type editReactionOption struct { } // PostIssueReaction add a reaction to an issue -func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction string) (*Reaction, error) { +func (c *Client) PostIssueReaction(owner, repo string, index int64, reaction string) (*Reaction, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return nil, err + return nil, nil, err } reactionResponse := new(Reaction) body, err := json.Marshal(&editReactionOption{Reaction: reaction}) if err != nil { - return nil, err + return nil, nil, err } - return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body), reactionResponse) + return reactionResponse, resp, err } // DeleteIssueReaction remove a reaction from an issue -func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction string) error { +func (c *Client) DeleteIssueReaction(owner, repo string, index int64, reaction string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return err + return nil, err } body, err := json.Marshal(&editReactionOption{Reaction: reaction}) if err != nil { - return err + return nil, err } - _, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/reactions", owner, repo, index), jsonHeader, bytes.NewReader(body)) + return resp, err } // PostIssueCommentReaction add a reaction to a comment of an issue -func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Reaction, error) { +func (c *Client) PostIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Reaction, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return nil, err + return nil, nil, err } reactionResponse := new(Reaction) body, err := json.Marshal(&editReactionOption{Reaction: reaction}) if err != nil { - return nil, err + return nil, nil, err } - return reactionResponse, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), jsonHeader, bytes.NewReader(body), reactionResponse) + return reactionResponse, resp, err } // DeleteIssueCommentReaction remove a reaction from a comment of an issue -func (c *Client) DeleteIssueCommentReaction(owner, repo string, commentID int64, reaction string) error { +func (c *Client) DeleteIssueCommentReaction(owner, repo string, commentID int64, reaction string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return err + return nil, err } - // swagger:operation DELETE /repos/{owner}/{repo}/issues/comments/{id}/reactions issue issueDeleteCommentReaction body, err := json.Marshal(&editReactionOption{Reaction: reaction}) if err != nil { - return err + return nil, err } - _, err = c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), + _, resp, err := c.getResponse("DELETE", + fmt.Sprintf("/repos/%s/%s/issues/comments/%d/reactions", owner, repo, commentID), jsonHeader, bytes.NewReader(body)) - return err + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go b/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go index 8b8f178de5c3..fac2c07efdcb 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_stopwatch.go @@ -16,27 +16,28 @@ type StopWatch struct { } // GetMyStopwatches list all stopwatches -func (c *Client) GetMyStopwatches() ([]*StopWatch, error) { +func (c *Client) GetMyStopwatches() ([]*StopWatch, *Response, error) { stopwatches := make([]*StopWatch, 0, 1) - return stopwatches, c.getParsedResponse("GET", "/user/stopwatches", nil, nil, &stopwatches) + resp, err := c.getParsedResponse("GET", "/user/stopwatches", nil, nil, &stopwatches) + return stopwatches, resp, err } // DeleteIssueStopwatch delete / cancel a specific stopwatch -func (c *Client) DeleteIssueStopwatch(owner, repo string, index int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/delete", owner, repo, index), nil, nil) - return err +func (c *Client) DeleteIssueStopwatch(owner, repo string, index int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/delete", owner, repo, index), nil, nil) + return resp, err } // StartIssueStopWatch starts a stopwatch for an existing issue for a given // repository -func (c *Client) StartIssueStopWatch(owner, repo string, index int64) error { - _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/start", owner, repo, index), nil, nil) - return err +func (c *Client) StartIssueStopWatch(owner, repo string, index int64) (*Response, error) { + _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/start", owner, repo, index), nil, nil) + return resp, err } // StopIssueStopWatch stops an existing stopwatch for an issue in a given // repository -func (c *Client) StopIssueStopWatch(owner, repo string, index int64) error { - _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/stop", owner, repo, index), nil, nil) - return err +func (c *Client) StopIssueStopWatch(owner, repo string, index int64) (*Response, error) { + _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/stopwatch/stop", owner, repo, index), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_subscription.go b/vendor/code.gitea.io/sdk/gitea/issue_subscription.go index b7980cf9a100..52e67ed44de7 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_subscription.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_subscription.go @@ -10,73 +10,75 @@ import ( ) // GetIssueSubscribers get list of users who subscribed on an issue -func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User, error) { +func (c *Client) GetIssueSubscribers(owner, repo string, index int64) ([]*User, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return nil, err + return nil, nil, err } subscribers := make([]*User, 0, 10) - return subscribers, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions", owner, repo, index), nil, nil, &subscribers) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions", owner, repo, index), nil, nil, &subscribers) + return subscribers, resp, err } // AddIssueSubscription Subscribe user to issue -func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) error { +func (c *Client) AddIssueSubscription(owner, repo string, index int64, user string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return err + return nil, err } - status, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) + status, resp, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) if err != nil { - return err + return resp, err } if status == http.StatusCreated { - return nil + return resp, nil } if status == http.StatusOK { - return fmt.Errorf("already subscribed") + return resp, fmt.Errorf("already subscribed") } - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } // DeleteIssueSubscription unsubscribe user from issue -func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) error { +func (c *Client) DeleteIssueSubscription(owner, repo string, index int64, user string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { - return err + return nil, err } - status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) + status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/%s", owner, repo, index, user), nil, nil) if err != nil { - return err + return resp, err } if status == http.StatusCreated { - return nil + return resp, nil } if status == http.StatusOK { - return fmt.Errorf("already unsubscribed") + return resp, fmt.Errorf("already unsubscribed") } - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } // CheckIssueSubscription check if current user is subscribed to an issue -func (c *Client) CheckIssueSubscription(owner, repo string, index int64) (*WatchInfo, error) { +func (c *Client) CheckIssueSubscription(owner, repo string, index int64) (*WatchInfo, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/subscriptions/check", owner, repo, index), nil, nil, wi) + return wi, resp, err } // IssueSubscribe subscribe current user to an issue -func (c *Client) IssueSubscribe(owner, repo string, index int64) error { - u, err := c.GetMyUserInfo() +func (c *Client) IssueSubscribe(owner, repo string, index int64) (*Response, error) { + u, _, err := c.GetMyUserInfo() if err != nil { - return err + return nil, err } return c.AddIssueSubscription(owner, repo, index, u.UserName) } // IssueUnSubscribe unsubscribe current user from an issue -func (c *Client) IssueUnSubscribe(owner, repo string, index int64) error { - u, err := c.GetMyUserInfo() +func (c *Client) IssueUnSubscribe(owner, repo string, index int64) (*Response, error) { + u, _, err := c.GetMyUserInfo() if err != nil { - return err + return nil, err } return c.DeleteIssueSubscription(owner, repo, index, u.UserName) } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go index d4b6af62ba11..481c831d7bc4 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go @@ -26,21 +26,33 @@ type TrackedTime struct { } // GetUserTrackedTimes list tracked times of a user -func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, error) { +func (c *Client) GetUserTrackedTimes(owner, repo, user string) ([]*TrackedTime, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, nil, err + } times := make([]*TrackedTime, 0, 10) - return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times/%s", owner, repo, user), nil, nil, ×) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times/%s", owner, repo, user), nil, nil, ×) + return times, resp, err } // GetRepoTrackedTimes list tracked times of a repository -func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, error) { +func (c *Client) GetRepoTrackedTimes(owner, repo string) ([]*TrackedTime, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, nil, err + } times := make([]*TrackedTime, 0, 10) - return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, ×) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/times", owner, repo), nil, nil, ×) + return times, resp, err } // GetMyTrackedTimes list tracked times of the current user -func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, error) { +func (c *Client) GetMyTrackedTimes() ([]*TrackedTime, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, nil, err + } times := make([]*TrackedTime, 0, 10) - return times, c.getParsedResponse("GET", "/user/times", nil, nil, ×) + resp, err := c.getParsedResponse("GET", "/user/times", nil, nil, ×) + return times, resp, err } // AddTimeOption options for adding time to an issue @@ -62,17 +74,22 @@ func (opt AddTimeOption) Validate() error { } // AddTime adds time to issue with the given index -func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, error) { +func (c *Client) AddTime(owner, repo string, index int64, opt AddTimeOption) (*TrackedTime, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, nil, err + } if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } t := new(TrackedTime) - return t, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), jsonHeader, bytes.NewReader(body), t) + return t, resp, err } // ListTrackedTimesOptions options for listing repository's tracked times @@ -81,20 +98,30 @@ type ListTrackedTimesOptions struct { } // ListTrackedTimes list tracked times of a single issue for a given repository -func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrackedTimesOptions) ([]*TrackedTime, error) { +func (c *Client) ListTrackedTimes(owner, repo string, index int64, opt ListTrackedTimesOptions) ([]*TrackedTime, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, nil, err + } opt.setDefaults() 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, ×) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times?%s", owner, repo, index, opt.getURLQuery().Encode()), nil, nil, ×) + return times, resp, err } // 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) - return err +func (c *Client) ResetIssueTime(owner, repo string, index int64) (*Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil) + return resp, err } // DeleteTime delete a specific tracked time by id of a single issue for a given repository -func (c *Client) DeleteTime(owner, repo string, index, timeID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil) - return err +func (c *Client) DeleteTime(owner, repo string, index, timeID int64) (*Response, error) { + if err := c.CheckServerVersionConstraint(">=1.11.0"); err != nil { + return nil, err + } + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/times/%d", owner, repo, index, timeID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/notifications.go b/vendor/code.gitea.io/sdk/gitea/notifications.go index c966b7e3a038..8f69cb3aae8a 100644 --- a/vendor/code.gitea.io/sdk/gitea/notifications.go +++ b/vendor/code.gitea.io/sdk/gitea/notifications.go @@ -103,92 +103,96 @@ func (opt MarkNotificationOptions) Validate(c *Client) error { } // CheckNotifications list users's notification threads -func (c *Client) CheckNotifications() (int64, error) { +func (c *Client) CheckNotifications() (int64, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return 0, err + return 0, nil, err } new := struct { New int64 `json:"new"` }{} - return new.New, c.getParsedResponse("GET", "/notifications/new", jsonHeader, nil, &new) + resp, err := c.getParsedResponse("GET", "/notifications/new", jsonHeader, nil, &new) + return new.New, resp, err } // GetNotification get notification thread by ID -func (c *Client) GetNotification(id int64) (*NotificationThread, error) { +func (c *Client) GetNotification(id int64) (*NotificationThread, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } thread := new(NotificationThread) - return thread, c.getParsedResponse("GET", fmt.Sprintf("/notifications/threads/%d", id), nil, nil, thread) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/notifications/threads/%d", id), nil, nil, thread) + return thread, resp, err } // ReadNotification mark notification thread as read by ID // It optionally takes a second argument if status has to be set other than 'read' -func (c *Client) ReadNotification(id int64, status ...NotifyStatus) error { +func (c *Client) ReadNotification(id int64, status ...NotifyStatus) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return err + return nil, err } link := fmt.Sprintf("/notifications/threads/%d", id) if len(status) != 0 { link += fmt.Sprintf("?to-status=%s", status[0]) } - _, err := c.getResponse("PATCH", link, nil, nil) - return err + _, resp, err := c.getResponse("PATCH", link, nil, nil) + return resp, err } // ListNotifications list users's notification threads -func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, error) { - if err := opt.Validate(c); err != nil { - return nil, err - } +func (c *Client) ListNotifications(opt ListNotificationOptions) ([]*NotificationThread, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err + } + if err := opt.Validate(c); err != nil { + return nil, nil, err } link, _ := url.Parse("/notifications") link.RawQuery = opt.QueryEncode() threads := make([]*NotificationThread, 0, 10) - return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &threads) + return threads, resp, err } // ReadNotifications mark notification threads as read -func (c *Client) ReadNotifications(opt MarkNotificationOptions) error { - if err := opt.Validate(c); err != nil { - return err - } +func (c *Client) ReadNotifications(opt MarkNotificationOptions) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return err + return nil, err + } + if err := opt.Validate(c); err != nil { + return nil, err } link, _ := url.Parse("/notifications") link.RawQuery = opt.QueryEncode() - _, err := c.getResponse("PUT", link.String(), nil, nil) - return err + _, resp, err := c.getResponse("PUT", link.String(), nil, nil) + return resp, err } // ListRepoNotifications list users's notification threads on a specific repo -func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, error) { - if err := opt.Validate(c); err != nil { - return nil, err - } +func (c *Client) ListRepoNotifications(owner, reponame string, opt ListNotificationOptions) ([]*NotificationThread, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err + } + if err := opt.Validate(c); err != nil { + return nil, nil, err } link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame)) link.RawQuery = opt.QueryEncode() threads := make([]*NotificationThread, 0, 10) - return threads, c.getParsedResponse("GET", link.String(), nil, nil, &threads) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &threads) + return threads, resp, err } // ReadRepoNotifications mark notification threads as read on a specific repo -func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) error { - if err := opt.Validate(c); err != nil { - return err - } +func (c *Client) ReadRepoNotifications(owner, reponame string, opt MarkNotificationOptions) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return err + return nil, err + } + if err := opt.Validate(c); err != nil { + return nil, err } link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/notifications", owner, reponame)) link.RawQuery = opt.QueryEncode() - _, err := c.getResponse("PUT", link.String(), nil, nil) - return err + _, resp, err := c.getResponse("PUT", link.String(), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/oauth2.go b/vendor/code.gitea.io/sdk/gitea/oauth2.go index 527535d046ab..80b154740548 100644 --- a/vendor/code.gitea.io/sdk/gitea/oauth2.go +++ b/vendor/code.gitea.io/sdk/gitea/oauth2.go @@ -33,55 +33,59 @@ type CreateOauth2Option struct { } // 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 +func (c *Client) CreateOauth2(opt CreateOauth2Option) (*Oauth2, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } oauth := new(Oauth2) - return oauth, c.getParsedResponse("POST", "/user/applications/oauth2", jsonHeader, bytes.NewReader(body), oauth) + resp, err := c.getParsedResponse("POST", "/user/applications/oauth2", jsonHeader, bytes.NewReader(body), oauth) + return oauth, resp, err } // UpdateOauth2 a specific Oauth2 Application by ID and return a completed Oauth2 object. -func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, error) { - if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { - return nil, e +func (c *Client) UpdateOauth2(oauth2id int64, opt CreateOauth2Option) (*Oauth2, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } oauth := new(Oauth2) - return oauth, c.getParsedResponse("PATCH", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), jsonHeader, bytes.NewReader(body), oauth) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), jsonHeader, bytes.NewReader(body), oauth) + return oauth, resp, err } // GetOauth2 a specific Oauth2 Application by ID. -func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, error) { - if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { - return nil, e +func (c *Client) GetOauth2(oauth2id int64) (*Oauth2, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return nil, nil, err } oauth2s := &Oauth2{} - return oauth2s, c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil, &oauth2s) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil, &oauth2s) + return oauth2s, resp, err } // ListOauth2 all of your Oauth2 Applications. -func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, error) { - if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { - return nil, e +func (c *Client) ListOauth2(opt ListOauth2Option) ([]*Oauth2, *Response, error) { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return nil, nil, err } 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/applications/oauth2?%s", opt.getURLQuery().Encode()), nil, nil, &oauth2s) + return oauth2s, resp, err } // DeleteOauth2 delete an Oauth2 application by ID -func (c *Client) DeleteOauth2(oauth2id int64) error { - if e := c.CheckServerVersionConstraint(">=1.12.0"); e != nil { - return e +func (c *Client) DeleteOauth2(oauth2id int64) (*Response, error) { + if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { + return nil, err } - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil) - return err + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/applications/oauth2/%d", oauth2id), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/org.go b/vendor/code.gitea.io/sdk/gitea/org.go index 750953e45898..ed6c678e64b0 100644 --- a/vendor/code.gitea.io/sdk/gitea/org.go +++ b/vendor/code.gitea.io/sdk/gitea/org.go @@ -43,23 +43,26 @@ type ListOrgsOptions struct { } // ListMyOrgs list all of current user's organizations -func (c *Client) ListMyOrgs(opt ListOrgsOptions) ([]*Organization, error) { +func (c *Client) ListMyOrgs(opt ListOrgsOptions) ([]*Organization, *Response, error) { opt.setDefaults() orgs := make([]*Organization, 0, opt.PageSize) - return orgs, c.getParsedResponse("GET", fmt.Sprintf("/user/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/orgs?%s", opt.getURLQuery().Encode()), nil, nil, &orgs) + return orgs, resp, err } // ListUserOrgs list all of some user's organizations -func (c *Client) ListUserOrgs(user string, opt ListOrgsOptions) ([]*Organization, error) { +func (c *Client) ListUserOrgs(user string, opt ListOrgsOptions) ([]*Organization, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs?%s", user, opt.getURLQuery().Encode()), nil, nil, &orgs) + return orgs, resp, err } // GetOrg get one organization by name -func (c *Client) GetOrg(orgname string) (*Organization, error) { +func (c *Client) GetOrg(orgname string) (*Organization, *Response, error) { org := new(Organization) - return org, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org) + return org, resp, err } // CreateOrgOption options for creating an organization @@ -89,16 +92,17 @@ func (opt CreateOrgOption) Validate() error { } // CreateOrg creates an organization -func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, error) { +func (c *Client) CreateOrg(opt CreateOrgOption) (*Organization, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } org := new(Organization) - return org, c.getParsedResponse("POST", "/orgs", jsonHeader, bytes.NewReader(body), org) + resp, err := c.getParsedResponse("POST", "/orgs", jsonHeader, bytes.NewReader(body), org) + return org, resp, err } // EditOrgOption options for editing an organization @@ -119,20 +123,20 @@ func (opt EditOrgOption) Validate() error { } // EditOrg modify one organization via options -func (c *Client) EditOrg(orgname string, opt EditOrgOption) error { +func (c *Client) EditOrg(orgname string, opt EditOrgOption) (*Response, error) { if err := opt.Validate(); err != nil { - return err + return nil, err } body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body)) + return resp, err } // DeleteOrg deletes an organization -func (c *Client) DeleteOrg(orgname string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, nil) - return err +func (c *Client) DeleteOrg(orgname string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/org_member.go b/vendor/code.gitea.io/sdk/gitea/org_member.go index 9e1bf7768c92..0f5b54296720 100644 --- a/vendor/code.gitea.io/sdk/gitea/org_member.go +++ b/vendor/code.gitea.io/sdk/gitea/org_member.go @@ -11,9 +11,9 @@ import ( ) // 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 +func (c *Client) DeleteOrgMembership(org, user string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) + return resp, err } // ListOrgMembershipOption list OrgMembership options @@ -22,77 +22,80 @@ type ListOrgMembershipOption struct { } // ListOrgMembership list an organization's members -func (c *Client) ListOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) { +func (c *Client) ListOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users) + return users, resp, err } // ListPublicOrgMembership list an organization's members -func (c *Client) ListPublicOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, error) { +func (c *Client) ListPublicOrgMembership(org string, opt ListOrgMembershipOption) ([]*User, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &users) + return users, resp, err } // CheckOrgMembership Check if a user is a member of an organization -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) +func (c *Client) CheckOrgMembership(org, user string) (bool, *Response, error) { + status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/orgs/%s/members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) if err != nil { - return false, err + return false, resp, err } switch status { case http.StatusNoContent: - return true, nil + return true, resp, nil case http.StatusNotFound: - return false, nil + return false, resp, nil default: - return false, fmt.Errorf("unexpected Status: %d", status) + return false, resp, fmt.Errorf("unexpected Status: %d", status) } } // CheckPublicOrgMembership Check if a user is a member of an organization -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) +func (c *Client) CheckPublicOrgMembership(org, user string) (bool, *Response, error) { + status, resp, 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 + return false, resp, err } switch status { case http.StatusNoContent: - return true, nil + return true, resp, nil case http.StatusNotFound: - return false, nil + return false, resp, nil default: - return false, fmt.Errorf("unexpected Status: %d", status) + return false, resp, fmt.Errorf("unexpected Status: %d", status) } } // SetPublicOrgMembership publicize/conceal a user's membership -func (c *Client) SetPublicOrgMembership(org, user string, visible bool) error { +func (c *Client) SetPublicOrgMembership(org, user string, visible bool) (*Response, error) { var ( status int err error + resp *Response ) if visible { - status, err = c.getStatusCode("PUT", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) + status, resp, err = c.getStatusCode("PUT", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) } else { - status, err = c.getStatusCode("DELETE", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) + status, resp, err = c.getStatusCode("DELETE", fmt.Sprintf("/orgs/%s/public_members/%s", url.PathEscape(org), url.PathEscape(user)), nil, nil) } if err != nil { - return err + return resp, err } switch status { case http.StatusNoContent: - return nil + return resp, nil case http.StatusNotFound: - return fmt.Errorf("forbidden") + return resp, fmt.Errorf("forbidden") default: - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } } diff --git a/vendor/code.gitea.io/sdk/gitea/org_team.go b/vendor/code.gitea.io/sdk/gitea/org_team.go index 73e29be924c5..148d2c2c3e6e 100644 --- a/vendor/code.gitea.io/sdk/gitea/org_team.go +++ b/vendor/code.gitea.io/sdk/gitea/org_team.go @@ -29,23 +29,26 @@ type ListTeamsOptions struct { } // ListOrgTeams lists all teams of an organization -func (c *Client) ListOrgTeams(org string, opt ListTeamsOptions) ([]*Team, error) { +func (c *Client) ListOrgTeams(org string, opt ListTeamsOptions) ([]*Team, *Response, error) { opt.setDefaults() teams := make([]*Team, 0, opt.PageSize) - return teams, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams?%s", org, opt.getURLQuery().Encode()), nil, nil, &teams) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/teams?%s", org, opt.getURLQuery().Encode()), nil, nil, &teams) + return teams, resp, err } // ListMyTeams lists all the teams of the current user -func (c *Client) ListMyTeams(opt *ListTeamsOptions) ([]*Team, error) { +func (c *Client) ListMyTeams(opt *ListTeamsOptions) ([]*Team, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/teams?%s", opt.getURLQuery().Encode()), nil, nil, &teams) + return teams, resp, err } // GetTeam gets a team by ID -func (c *Client) GetTeam(id int64) (*Team, error) { +func (c *Client) GetTeam(id int64) (*Team, *Response, error) { t := new(Team) - return t, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d", id), nil, nil, t) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d", id), nil, nil, t) + return t, resp, err } // CreateTeamOption options for creating a team @@ -79,16 +82,17 @@ func (opt CreateTeamOption) Validate() error { } // CreateTeam creates a team for an organization -func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, error) { +func (c *Client) CreateTeam(org string, opt CreateTeamOption) (*Team, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } t := new(Team) - return t, c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/teams", org), jsonHeader, bytes.NewReader(body), t) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/orgs/%s/teams", org), jsonHeader, bytes.NewReader(body), t) + return t, resp, err } // EditTeamOption options for editing a team @@ -122,22 +126,22 @@ func (opt EditTeamOption) Validate() error { } // EditTeam edits a team of an organization -func (c *Client) EditTeam(id int64, opt EditTeamOption) error { +func (c *Client) EditTeam(id int64, opt EditTeamOption) (*Response, error) { if err := opt.Validate(); err != nil { - return err + return nil, err } body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PATCH", fmt.Sprintf("/teams/%d", id), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PATCH", fmt.Sprintf("/teams/%d", id), jsonHeader, bytes.NewReader(body)) + return resp, err } // DeleteTeam deletes a team of an organization -func (c *Client) DeleteTeam(id int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d", id), nil, nil) - return err +func (c *Client) DeleteTeam(id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d", id), nil, nil) + return resp, err } // ListTeamMembersOptions options for listing team's members @@ -146,28 +150,30 @@ type ListTeamMembersOptions struct { } // ListTeamMembers lists all members of a team -func (c *Client) ListTeamMembers(id int64, opt ListTeamMembersOptions) ([]*User, error) { +func (c *Client) ListTeamMembers(id int64, opt ListTeamMembersOptions) ([]*User, *Response, error) { opt.setDefaults() members := make([]*User, 0, opt.PageSize) - return members, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members?%s", id, opt.getURLQuery().Encode()), nil, nil, &members) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members?%s", id, opt.getURLQuery().Encode()), nil, nil, &members) + return members, resp, err } // GetTeamMember gets a member of a team -func (c *Client) GetTeamMember(id int64, user string) (*User, error) { +func (c *Client) GetTeamMember(id int64, user string) (*User, *Response, error) { m := new(User) - return m, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil, m) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil, m) + return m, resp, err } // AddTeamMember adds a member to a team -func (c *Client) AddTeamMember(id int64, user string) error { - _, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) - return err +func (c *Client) AddTeamMember(id int64, user string) (*Response, error) { + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) + return resp, err } // RemoveTeamMember removes a member from a team -func (c *Client) RemoveTeamMember(id int64, user string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) - return err +func (c *Client) RemoveTeamMember(id int64, user string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/members/%s", id, user), nil, nil) + return resp, err } // ListTeamRepositoriesOptions options for listing team's repositories @@ -176,20 +182,21 @@ type ListTeamRepositoriesOptions struct { } // ListTeamRepositories lists all repositories of a team -func (c *Client) ListTeamRepositories(id int64, opt ListTeamRepositoriesOptions) ([]*Repository, error) { +func (c *Client) ListTeamRepositories(id int64, opt ListTeamRepositoriesOptions) ([]*Repository, *Response, error) { opt.setDefaults() repos := make([]*Repository, 0, opt.PageSize) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos?%s", id, opt.getURLQuery().Encode()), nil, nil, &repos) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/teams/%d/repos?%s", id, opt.getURLQuery().Encode()), nil, nil, &repos) + return repos, resp, err } // AddTeamRepository adds a repository to a team -func (c *Client) AddTeamRepository(id int64, org, repo string) error { - _, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) - return err +func (c *Client) AddTeamRepository(id int64, org, repo string) (*Response, error) { + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) + return resp, err } // RemoveTeamRepository removes a repository from a team -func (c *Client) RemoveTeamRepository(id int64, org, repo string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) - return err +func (c *Client) RemoveTeamRepository(id int64, org, repo string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/teams/%d/repos/%s/%s", id, org, repo), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go index ff6f90f6d3a6..24d70e2fafe5 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull.go +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -98,19 +98,21 @@ func (opt *ListPullRequestsOptions) QueryEncode() string { } // ListRepoPullRequests list PRs of one repository -func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { +func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, *Response, error) { opt.setDefaults() 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) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &prs) + return prs, resp, err } // GetPullRequest get information of one PR -func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest, error) { +func (c *Client) GetPullRequest(owner, repo string, index int64) (*PullRequest, *Response, error) { pr := new(PullRequest) - return pr, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), nil, nil, pr) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), nil, nil, pr) + return pr, resp, err } // CreatePullRequestOption options when creating a pull request @@ -127,14 +129,16 @@ type CreatePullRequestOption struct { } // CreatePullRequest create pull request with options -func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOption) (*PullRequest, error) { +func (c *Client) CreatePullRequest(owner, repo string, opt CreatePullRequestOption) (*PullRequest, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } pr := new(PullRequest) - return pr, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), jsonHeader, bytes.NewReader(body), pr) + return pr, resp, err } // EditPullRequestOption options when modify pull request @@ -164,17 +168,19 @@ func (opt EditPullRequestOption) Validate(c *Client) error { } // EditPullRequest modify pull request with PR id and options -func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, error) { +func (c *Client) EditPullRequest(owner, repo string, index int64, opt EditPullRequestOption) (*PullRequest, *Response, error) { if err := opt.Validate(c); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } pr := new(PullRequest) - return pr, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), + resp, err := c.getParsedResponse("PATCH", + fmt.Sprintf("/repos/%s/%s/pulls/%d", owner, repo, index), jsonHeader, bytes.NewReader(body), pr) + return pr, resp, err } // MergePullRequestOption options when merging a pull request @@ -195,41 +201,41 @@ func (opt MergePullRequestOption) Validate(c *Client) error { } // MergePullRequest merge a PR to repository by PR id -func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, error) { +func (c *Client) MergePullRequest(owner, repo string, index int64, opt MergePullRequestOption) (bool, *Response, error) { if err := opt.Validate(c); err != nil { - return false, err + return false, nil, err } body, err := json.Marshal(&opt) if err != nil { - return false, err + return false, nil, err } - status, err := c.getStatusCode("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), jsonHeader, bytes.NewReader(body)) + status, resp, err := c.getStatusCode("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), jsonHeader, bytes.NewReader(body)) if err != nil { - return false, err + return false, resp, err } - return status == 200, nil + return status == 200, resp, nil } // IsPullRequestMerged test if one PR is merged to one repository -func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, error) { - statusCode, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) +func (c *Client) IsPullRequestMerged(owner, repo string, index int64) (bool, *Response, error) { + status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) if err != nil { - return false, err + return false, resp, err } - return statusCode == 204, nil + return status == 204, resp, nil } // getPullRequestDiffOrPatch gets the patch or diff file as bytes for a PR -func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64) ([]byte, error) { +func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64) ([]byte, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - r, err2 := c.GetRepo(owner, repo) + r, _, err2 := c.GetRepo(owner, repo) if err2 != nil { - return nil, err + return nil, nil, err } if r.Private { - return nil, err + return nil, nil, err } return c.getWebResponse("GET", fmt.Sprintf("/%s/%s/pulls/%d.%s", owner, repo, index, kind), nil) } @@ -237,11 +243,11 @@ func (c *Client) getPullRequestDiffOrPatch(owner, repo, kind string, index int64 } // GetPullRequestPatch gets the .patch file as bytes for a PR -func (c *Client) GetPullRequestPatch(owner, repo string, index int64) ([]byte, error) { +func (c *Client) GetPullRequestPatch(owner, repo string, index int64) ([]byte, *Response, error) { return c.getPullRequestDiffOrPatch(owner, repo, "patch", index) } // GetPullRequestDiff gets the .diff file as bytes for a PR -func (c *Client) GetPullRequestDiff(owner, repo string, index int64) ([]byte, error) { +func (c *Client) GetPullRequestDiff(owner, repo string, index int64) ([]byte, *Response, error) { return c.getPullRequestDiffOrPatch(owner, repo, "diff", index) } diff --git a/vendor/code.gitea.io/sdk/gitea/pull_review.go b/vendor/code.gitea.io/sdk/gitea/pull_review.go index 169ac1a28aa9..e44dc7df58c9 100644 --- a/vendor/code.gitea.io/sdk/gitea/pull_review.go +++ b/vendor/code.gitea.io/sdk/gitea/pull_review.go @@ -131,9 +131,9 @@ func (opt CreatePullReviewComment) Validate() error { } // ListPullReviews lists all reviews of a pull request -func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, error) { +func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullReviewsOptions) ([]*PullReview, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } opt.setDefaults() rs := make([]*PullReview, 0, opt.PageSize) @@ -141,72 +141,79 @@ func (c *Client) ListPullReviews(owner, repo string, index int64, opt ListPullRe link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index)) link.RawQuery = opt.ListOptions.getURLQuery().Encode() - return rs, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rs) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rs) + return rs, resp, err } // GetPullReview gets a specific review of a pull request -func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview, error) { +func (c *Client) GetPullReview(owner, repo string, index, id int64) (*PullReview, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil, &r) + return r, resp, err } // ListPullReviewComments lists all comments of a pull request review -func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]*PullReviewComment, error) { +func (c *Client) ListPullReviewComments(owner, repo string, index, id int64) ([]*PullReviewComment, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } rcl := make([]*PullReviewComment, 0, 4) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d/comments", owner, repo, index, id)) - return rcl, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rcl) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &rcl) + return rcl, resp, err } // DeletePullReview delete a specific review from a pull request -func (c *Client) DeletePullReview(owner, repo string, index, id int64) error { +func (c *Client) DeletePullReview(owner, repo string, index, id int64) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return err + return nil, err } - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil) - return err + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, nil) + return resp, err } // CreatePullReview create a review to an pull request -func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePullReviewOptions) (*PullReview, error) { +func (c *Client) CreatePullReview(owner, repo string, index int64, opt CreatePullReviewOptions) (*PullReview, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } r := new(PullReview) - return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews", owner, repo, index), jsonHeader, bytes.NewReader(body), r) + return r, resp, err } // SubmitPullReview submit a pending review to an pull request -func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt SubmitPullReviewOptions) (*PullReview, error) { +func (c *Client) SubmitPullReview(owner, repo string, index, id int64, opt SubmitPullReviewOptions) (*PullReview, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } r := new(PullReview) - return r, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), + resp, err := c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/pulls/%d/reviews/%d", owner, repo, index, id), jsonHeader, bytes.NewReader(body), r) + return r, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/release.go b/vendor/code.gitea.io/sdk/gitea/release.go index 44cdc00d2099..3ce204a1a10d 100644 --- a/vendor/code.gitea.io/sdk/gitea/release.go +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -36,22 +36,22 @@ type ListReleasesOptions struct { } // ListReleases list releases of a repository -func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Release, error) { +func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Release, *Response, error) { opt.setDefaults() releases := make([]*Release, 0, opt.PageSize) - err := c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/releases?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &releases) - return releases, err + return releases, resp, err } // GetRelease get a release of a repository -func (c *Client) GetRelease(user, repo string, id int64) (*Release, error) { +func (c *Client) GetRelease(user, repo string, id int64) (*Release, *Response, error) { r := new(Release) - err := c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), nil, nil, &r) - return r, err + return r, resp, err } // CreateReleaseOption options when creating a release @@ -73,19 +73,19 @@ func (opt CreateReleaseOption) Validate() error { } // CreateRelease create a release -func (c *Client) CreateRelease(user, repo string, opt CreateReleaseOption) (*Release, error) { +func (c *Client) CreateRelease(user, repo string, opt CreateReleaseOption) (*Release, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(opt) if err != nil { - return nil, err + return nil, nil, err } r := new(Release) - err = c.getParsedResponse("POST", + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/releases", user, repo), jsonHeader, bytes.NewReader(body), r) - return r, err + return r, resp, err } // EditReleaseOption options when editing a release @@ -99,22 +99,22 @@ type EditReleaseOption struct { } // EditRelease edit a release -func (c *Client) EditRelease(user, repo string, id int64, form EditReleaseOption) (*Release, error) { +func (c *Client) EditRelease(user, repo string, id int64, form EditReleaseOption) (*Release, *Response, error) { body, err := json.Marshal(form) if err != nil { - return nil, err + return nil, nil, err } r := new(Release) - err = c.getParsedResponse("PATCH", + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), jsonHeader, bytes.NewReader(body), r) - return r, err + return r, resp, err } // DeleteRelease delete a release from a repository -func (c *Client) DeleteRelease(user, repo string, id int64) error { - _, err := c.getResponse("DELETE", +func (c *Client) DeleteRelease(user, repo string, id int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), nil, nil) - return err + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo.go b/vendor/code.gitea.io/sdk/gitea/repo.go index 3546ef26aa3a..c43272487359 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo.go +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -1,4 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. +// Copyright 2020 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. @@ -78,17 +79,19 @@ type ListReposOptions struct { } // ListMyRepos lists all repositories for the authenticated user that has access to. -func (c *Client) ListMyRepos(opt ListReposOptions) ([]*Repository, error) { +func (c *Client) ListMyRepos(opt ListReposOptions) ([]*Repository, *Response, error) { opt.setDefaults() repos := make([]*Repository, 0, opt.PageSize) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/user/repos?%s", opt.getURLQuery().Encode()), nil, nil, &repos) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/repos?%s", opt.getURLQuery().Encode()), nil, nil, &repos) + return repos, resp, err } // ListUserRepos list all repositories of one user by user's name -func (c *Client) ListUserRepos(user string, opt ListReposOptions) ([]*Repository, error) { +func (c *Client) ListUserRepos(user string, opt ListReposOptions) ([]*Repository, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos?%s", user, opt.getURLQuery().Encode()), nil, nil, &repos) + return repos, resp, err } // ListOrgReposOptions options for a organization's repositories @@ -97,10 +100,11 @@ type ListOrgReposOptions struct { } // ListOrgRepos list all repositories of one organization by organization's name -func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repository, error) { +func (c *Client) ListOrgRepos(org string, opt ListOrgReposOptions) ([]*Repository, *Response, error) { opt.setDefaults() repos := make([]*Repository, 0, opt.PageSize) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos?%s", org, opt.getURLQuery().Encode()), nil, nil, &repos) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos?%s", org, opt.getURLQuery().Encode()), nil, nil, &repos) + return repos, resp, err } // SearchRepoOptions options for searching repositories @@ -209,9 +213,9 @@ type searchRepoResponse struct { } // SearchRepos searches for repositories matching the given filters -func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) { +func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, *Response, error) { opt.setDefaults() - resp := new(searchRepoResponse) + repos := new(searchRepoResponse) link, _ := url.Parse("/repos/search") @@ -223,14 +227,14 @@ func (c *Client) SearchRepos(opt SearchRepoOptions) ([]*Repository, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil && opt.IsPrivate != nil { if *opt.IsPrivate { // private repos only not supported on gitea <= 1.11.x - return nil, err + return nil, nil, err } link.Query().Add("private", "false") } } - err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) - return resp.Repos, err + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &repos) + return repos.Repos, resp, err } // CreateRepoOption options when creating repository @@ -264,35 +268,38 @@ func (opt CreateRepoOption) Validate() error { } // CreateRepo creates a repository for authenticated user. -func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) { +func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } repo := new(Repository) - return repo, c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo) + resp, err := c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err } // CreateOrgRepo creates an organization repository for authenticated user. -func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, error) { +func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, *Response, error) { if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } repo := new(Repository) - return repo, c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err } // GetRepo returns information of a repository of given owner. -func (c *Client) GetRepo(owner, reponame string) (*Repository, error) { +func (c *Client) GetRepo(owner, reponame string) (*Repository, *Response, error) { repo := new(Repository) - return repo, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo) + return repo, resp, err } // EditRepoOption options when editing a repository's properties @@ -330,65 +337,40 @@ type EditRepoOption struct { } // EditRepo edit the properties of a repository -func (c *Client) EditRepo(owner, reponame string, opt EditRepoOption) (*Repository, error) { +func (c *Client) EditRepo(owner, reponame string, opt EditRepoOption) (*Repository, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } repo := new(Repository) - return repo, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s", owner, reponame), jsonHeader, bytes.NewReader(body), repo) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s", owner, reponame), jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err } // DeleteRepo deletes a repository of user or organization. -func (c *Client) DeleteRepo(owner, repo string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil) - return err -} - -// MigrateRepoOption options for migrating a repository from an external service -type MigrateRepoOption struct { - CloneAddr string `json:"clone_addr"` - AuthUsername string `json:"auth_username"` - AuthPassword string `json:"auth_password"` - UID int `json:"uid"` - RepoName string `json:"repo_name"` - Mirror bool `json:"mirror"` - Private bool `json:"private"` - Description string `json:"description"` -} - -// MigrateRepo migrates a repository from other Git hosting sources for the -// authenticated user. -// -// To migrate a repository for a organization, the authenticated user must be a -// owner of the specified organization. -func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, error) { - body, err := json.Marshal(&opt) - if err != nil { - return nil, err - } - repo := new(Repository) - return repo, c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo) +func (c *Client) DeleteRepo(owner, repo string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil) + return resp, err } // MirrorSync adds a mirrored repository to the mirror sync queue. -func (c *Client) MirrorSync(owner, repo string) error { - _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil) - return err +func (c *Client) MirrorSync(owner, repo string) (*Response, error) { + _, resp, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/mirror-sync", owner, repo), nil, nil) + return resp, err } // GetRepoLanguages return language stats of a repo -func (c *Client) GetRepoLanguages(owner, repo string) (map[string]int64, error) { +func (c *Client) GetRepoLanguages(owner, repo string) (map[string]int64, *Response, error) { langMap := make(map[string]int64) - data, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/languages", owner, repo), jsonHeader, nil) + data, resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/languages", owner, repo), jsonHeader, nil) if err != nil { - return nil, err + return nil, resp, err } if err = json.Unmarshal(data, &langMap); err != nil { - return nil, err + return nil, resp, err } - return langMap, nil + return langMap, resp, nil } // ArchiveType represent supported archive formats by gitea @@ -403,6 +385,6 @@ const ( // GetArchive get an archive of a repository by git reference // e.g.: ref -> master, 70b7c74b33, v1.2.1, ... -func (c *Client) GetArchive(owner, repo, ref string, ext ArchiveType) ([]byte, error) { +func (c *Client) GetArchive(owner, repo, ref string, ext ArchiveType) ([]byte, *Response, error) { return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/archive/%s%s", owner, repo, url.PathEscape(ref), ext), nil, nil) } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch.go b/vendor/code.gitea.io/sdk/gitea/repo_branch.go index a33f618d7083..0d6249e7d014 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch.go @@ -65,31 +65,33 @@ type ListRepoBranchesOptions struct { } // ListRepoBranches list all the branches of one repository -func (c *Client) ListRepoBranches(user, repo string, opt ListRepoBranchesOptions) ([]*Branch, error) { +func (c *Client) ListRepoBranches(user, repo string, opt ListRepoBranchesOptions) ([]*Branch, *Response, error) { opt.setDefaults() branches := make([]*Branch, 0, opt.PageSize) - return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &branches) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &branches) + return branches, resp, err } // GetRepoBranch get one branch's information of one repository -func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { +func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, *Response, error) { b := new(Branch) - if err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b); err != nil { - return nil, err + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b) + if err != nil { + return nil, resp, err } - return b, nil + return b, resp, nil } // DeleteRepoBranch delete a branch in a repository -func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, error) { +func (c *Client) DeleteRepoBranch(user, repo, branch string) (bool, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return false, err + return false, nil, err } - status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil) + status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil) if err != nil { - return false, err + return false, resp, err } - return status == 204, nil + return status == 204, resp, nil } // CreateBranchOption options when creating a branch in a repository @@ -115,17 +117,18 @@ func (opt CreateBranchOption) Validate() error { } // CreateBranch creates a branch for a user's repository -func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, error) { +func (c *Client) CreateBranch(owner, repo string, opt CreateBranchOption) (*Branch, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } if err := opt.Validate(); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } branch := new(Branch) - return branch, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branches", owner, repo), jsonHeader, bytes.NewReader(body), branch) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branches", owner, repo), jsonHeader, bytes.NewReader(body), branch) + return branch, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go index 31bba9c772d7..f4d47deda300 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch_protection.go @@ -91,56 +91,60 @@ type ListBranchProtectionsOptions struct { } // ListBranchProtections list branch protections for a repo -func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtectionsOptions) ([]*BranchProtection, error) { +func (c *Client) ListBranchProtections(owner, repo string, opt ListBranchProtectionsOptions) ([]*BranchProtection, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } - bps := make([]*BranchProtection, 0, 5) + bps := make([]*BranchProtection, 0, opt.PageSize) link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo)) link.RawQuery = opt.getURLQuery().Encode() - return bps, c.getParsedResponse("GET", link.String(), jsonHeader, nil, &bps) + resp, err := c.getParsedResponse("GET", link.String(), jsonHeader, nil, &bps) + return bps, resp, err } // GetBranchProtection gets a branch protection -func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, error) { +func (c *Client) GetBranchProtection(owner, repo, name string) (*BranchProtection, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } bp := new(BranchProtection) - return bp, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil, bp) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil, bp) + return bp, resp, err } // CreateBranchProtection creates a branch protection for a repo -func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProtectionOption) (*BranchProtection, error) { +func (c *Client) CreateBranchProtection(owner, repo string, opt CreateBranchProtectionOption) (*BranchProtection, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } bp := new(BranchProtection) body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } - return bp, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo), jsonHeader, bytes.NewReader(body), bp) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/branch_protections", owner, repo), jsonHeader, bytes.NewReader(body), bp) + return bp, resp, err } // EditBranchProtection edits a branch protection for a repo -func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchProtectionOption) (*BranchProtection, error) { +func (c *Client) EditBranchProtection(owner, repo, name string, opt EditBranchProtectionOption) (*BranchProtection, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } bp := new(BranchProtection) body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } - return bp, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), bp) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), bp) + return bp, resp, err } // DeleteBranchProtection deletes a branch protection for a repo -func (c *Client) DeleteBranchProtection(owner, repo, name string) error { +func (c *Client) DeleteBranchProtection(owner, repo, name string) (*Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return err + return nil, err } - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil) - return err + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/branch_protections/%s", owner, repo, name), jsonHeader, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go index fb01986f93db..63c4eafd5d79 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -16,24 +16,25 @@ type ListCollaboratorsOptions struct { } // ListCollaborators list a repository's collaborators -func (c *Client) ListCollaborators(user, repo string, opt ListCollaboratorsOptions) ([]*User, error) { +func (c *Client) ListCollaborators(user, repo string, opt ListCollaboratorsOptions) ([]*User, *Response, error) { opt.setDefaults() collaborators := make([]*User, 0, opt.PageSize) - return collaborators, c.getParsedResponse("GET", + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/collaborators?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &collaborators) + return collaborators, resp, 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) +func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, *Response, error) { + status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil) if err != nil { - return false, err + return false, resp, err } if status == 204 { - return true, nil + return true, resp, nil } - return false, nil + return false, resp, nil } // AddCollaboratorOption options when adding a user as a collaborator of a repository @@ -76,21 +77,21 @@ func (opt AddCollaboratorOption) Validate() error { } // AddCollaborator add some user as a collaborator of a repository -func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) error { +func (c *Client) AddCollaborator(user, repo, collaborator string, opt AddCollaboratorOption) (*Response, error) { if err := opt.Validate(); err != nil { - return err + return nil, err } body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), jsonHeader, bytes.NewReader(body)) + return resp, err } // DeleteCollaborator remove a collaborator from a repository -func (c *Client) DeleteCollaborator(user, repo, collaborator string) error { - _, err := c.getResponse("DELETE", +func (c *Client) DeleteCollaborator(user, repo, collaborator string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), nil, nil) - return err + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_commit.go b/vendor/code.gitea.io/sdk/gitea/repo_commit.go index 82ef3fa97e11..e17d0030b9dd 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_commit.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_commit.go @@ -55,9 +55,10 @@ type CommitDateOptions struct { } // GetSingleCommit returns a single commit -func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, error) { +func (c *Client) GetSingleCommit(user, repo, commitID string) (*Commit, *Response, error) { commit := new(Commit) - return commit, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/commits/%s", user, repo, commitID), nil, nil, &commit) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/commits/%s", user, repo, commitID), nil, nil, &commit) + return commit, resp, err } // ListCommitOptions list commit options @@ -77,10 +78,11 @@ func (opt *ListCommitOptions) QueryEncode() string { } // ListRepoCommits return list of commits from a repo -func (c *Client) ListRepoCommits(user, repo string, opt ListCommitOptions) ([]*Commit, error) { +func (c *Client) ListRepoCommits(user, repo string, opt ListCommitOptions) ([]*Commit, *Response, error) { link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/commits", user, repo)) opt.setDefaults() commits := make([]*Commit, 0, opt.PageSize) link.RawQuery = opt.QueryEncode() - return commits, c.getParsedResponse("GET", link.String(), nil, nil, &commits) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &commits) + return commits, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go index 18818592d7b6..94f216fdf956 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_file.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_file.go @@ -114,74 +114,76 @@ type FileDeleteResponse struct { // 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) { +func (c *Client) GetFile(user, repo, ref, tree string) ([]byte, *Response, error) { return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/raw/%s/%s", user, repo, ref, tree), nil, nil) } // 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) { +func (c *Client) GetContents(owner, repo, ref, filepath string) (*ContentsResponse, *Response, 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) - + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", owner, repo, filepath, ref), jsonHeader, nil, cr) + return cr, resp, err } // CreateFile create a file in a repository -func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, error) { +func (c *Client) CreateFile(owner, repo, filepath string, opt CreateFileOptions) (*FileResponse, *Response, error) { var err error if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, 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) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr) + return fr, resp, err } // UpdateFile update a file in a repository -func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, error) { +func (c *Client) UpdateFile(owner, repo, filepath string, opt UpdateFileOptions) (*FileResponse, *Response, error) { var err error if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, 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) + resp, err := c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body), fr) + return fr, resp, err } // DeleteFile delete a file from repository -func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) error { +func (c *Client) DeleteFile(owner, repo, filepath string, opt DeleteFileOptions) (*Response, error) { var err error if opt.BranchName, err = c.setDefaultBranchForOldVersions(owner, repo, opt.BranchName); err != nil { - return err + return nil, err } body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body)) + status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/contents/%s", owner, repo, filepath), jsonHeader, bytes.NewReader(body)) if err != nil { - return err + return resp, err } if status != 200 && status != 204 { - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } - return nil + return resp, nil } func (c *Client) setDefaultBranchForOldVersions(owner, repo, branch string) (string, error) { if len(branch) == 0 { // Gitea >= 1.12.0 Use DefaultBranch on "", mimic this for older versions - if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - r, err := c.GetRepo(owner, repo) + if c.CheckServerVersionConstraint(">=1.12.0") != nil { + r, _, err := c.GetRepo(owner, repo) if err != nil { return "", err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_key.go b/vendor/code.gitea.io/sdk/gitea/repo_key.go index 041df5da8f34..cfdfe0cd42f6 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_key.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_key.go @@ -45,32 +45,35 @@ func (opt *ListDeployKeysOptions) QueryEncode() string { } // ListDeployKeys list all the deploy keys of one repository -func (c *Client) ListDeployKeys(user, repo string, opt ListDeployKeysOptions) ([]*DeployKey, error) { +func (c *Client) ListDeployKeys(user, repo string, opt ListDeployKeysOptions) ([]*DeployKey, *Response, error) { link, _ := url.Parse(fmt.Sprintf("/repos/%s/%s/keys", user, repo)) opt.setDefaults() link.RawQuery = opt.QueryEncode() keys := make([]*DeployKey, 0, opt.PageSize) - return keys, c.getParsedResponse("GET", link.String(), nil, nil, &keys) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &keys) + return keys, resp, err } // GetDeployKey get one deploy key with key id -func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, error) { +func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, *Response, error) { key := new(DeployKey) - return key, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key) + return key, resp, err } // CreateDeployKey options when create one deploy key -func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, error) { +func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } key := new(DeployKey) - return key, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key) + return key, resp, err } // DeleteDeployKey delete deploy key with key id -func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil) - return err +func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_migrate.go b/vendor/code.gitea.io/sdk/gitea/repo_migrate.go new file mode 100644 index 000000000000..583d800d36ff --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_migrate.go @@ -0,0 +1,115 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package gitea + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// GitServiceType represents a git service +type GitServiceType string + +const ( + // GitServicePlain represents a plain git service + GitServicePlain GitServiceType = "git" + //GitServiceGithub represents github.com + GitServiceGithub GitServiceType = "github" + // GitServiceGitlab represents a gitlab service + GitServiceGitlab GitServiceType = "gitlab" + + // Not supported jet + // // GitServiceGitea represents a gitea service + // GitServiceGitea GitServiceType = "gitea" + // // GitServiceGogs represents a gogs service + // GitServiceGogs GitServiceType = "gogs" +) + +// MigrateRepoOption options for migrating a repository from an external service +type MigrateRepoOption struct { + RepoName string `json:"repo_name"` + RepoOwner string `json:"repo_owner"` + // deprecated use RepoOwner + RepoOwnerID int64 `json:"uid"` + CloneAddr string `json:"clone_addr"` + Service GitServiceType `json:"service"` + AuthUsername string `json:"auth_username"` + AuthPassword string `json:"auth_password"` + AuthToken string `json:"auth_token"` + Mirror bool `json:"mirror"` + Private bool `json:"private"` + Description string `json:"description"` + Wiki bool `json:"wiki"` + Milestones bool `json:"milestones"` + Labels bool `json:"labels"` + Issues bool `json:"issues"` + PullRequests bool `json:"pull_requests"` + Releases bool `json:"releases"` +} + +// Validate the MigrateRepoOption struct +func (opt *MigrateRepoOption) Validate() error { + // check user options + if len(opt.CloneAddr) == 0 { + return fmt.Errorf("CloneAddr required") + } + if len(opt.RepoName) == 0 { + return fmt.Errorf("RepoName required") + } else if len(opt.RepoName) > 100 { + return fmt.Errorf("RepoName to long") + } + if len(opt.Description) > 255 { + return fmt.Errorf("Description to long") + } + switch opt.Service { + case GitServiceGithub: + if len(opt.AuthToken) == 0 { + return fmt.Errorf("github require token authentication") + } + } + return nil +} + +// MigrateRepo migrates a repository from other Git hosting sources for the authenticated user. +// +// To migrate a repository for a organization, the authenticated user must be a +// owner of the specified organization. +func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, *Response, error) { + if err := opt.Validate(); err != nil { + return nil, nil, err + } + + if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { + if len(opt.AuthToken) != 0 { + // gitea <= 1.12 dont understand AuthToken + opt.AuthUsername = opt.AuthToken + opt.AuthPassword, opt.AuthToken = "", "" + } + if len(opt.RepoOwner) != 0 { + // gitea <= 1.12 dont understand RepoOwner + u, _, err := c.GetUserInfo(opt.RepoOwner) + if err != nil { + return nil, nil, err + } + opt.RepoOwnerID = u.ID + } else if opt.RepoOwnerID == 0 { + // gitea <= 1.12 require RepoOwnerID + u, _, err := c.GetMyUserInfo() + if err != nil { + return nil, nil, err + } + opt.RepoOwnerID = u.ID + } + } + + body, err := json.Marshal(&opt) + if err != nil { + return nil, nil, err + } + repo := new(Repository) + resp, err := c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_refs.go b/vendor/code.gitea.io/sdk/gitea/repo_refs.go index b946a100265b..fa1698a4999c 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_refs.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_refs.go @@ -26,44 +26,44 @@ type GitObject struct { } // GetRepoRef get one ref's information of one repository -func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, error) { +func (c *Client) GetRepoRef(user, repo, ref string) (*Reference, *Response, error) { ref = strings.TrimPrefix(ref, "refs/") r := new(Reference) - err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil, &r) if _, ok := err.(*json.UnmarshalTypeError); ok { // Multiple refs - return nil, errors.New("no exact match found for this ref") + return nil, resp, errors.New("no exact match found for this ref") } else if err != nil { - return nil, err + return nil, resp, err } - return r, nil + return r, resp, nil } // GetRepoRefs get list of ref's information of one repository -func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, error) { +func (c *Client) GetRepoRefs(user, repo, ref string) ([]*Reference, *Response, error) { ref = strings.TrimPrefix(ref, "refs/") - resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil) + data, resp, err := c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/git/refs/%s", user, repo, ref), nil, nil) if err != nil { - return nil, err + return nil, resp, err } // Attempt to unmarshal single returned ref. r := new(Reference) - refErr := json.Unmarshal(resp, r) + refErr := json.Unmarshal(data, r) if refErr == nil { - return []*Reference{r}, nil + return []*Reference{r}, resp, nil } // Attempt to unmarshal multiple refs. var rs []*Reference - refsErr := json.Unmarshal(resp, &rs) + refsErr := json.Unmarshal(data, &rs) if refsErr == nil { if len(rs) == 0 { - return nil, errors.New("unexpected response: an array of refs with length 0") + return nil, resp, errors.New("unexpected response: an array of refs with length 0") } - return rs, nil + return rs, resp, nil } - return nil, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr) + return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", refErr, refsErr) } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_tag.go b/vendor/code.gitea.io/sdk/gitea/repo_tag.go index b64d90b81e78..19eed5b9af3e 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_tag.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_tag.go @@ -23,8 +23,9 @@ type ListRepoTagsOptions struct { } // ListRepoTags list all the branches of one repository -func (c *Client) ListRepoTags(user, repo string, opt ListRepoTagsOptions) ([]*Tag, error) { +func (c *Client) ListRepoTags(user, repo string, opt ListRepoTagsOptions) ([]*Tag, *Response, error) { opt.setDefaults() tags := make([]*Tag, 0, opt.PageSize) - return tags, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &tags) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/tags?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, &tags) + return tags, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_topics.go b/vendor/code.gitea.io/sdk/gitea/repo_topics.go index 8d90e2691ef1..fd05d0899c65 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_topics.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_topics.go @@ -21,38 +21,38 @@ type topicsList struct { } // ListRepoTopics list all repository's topics -func (c *Client) ListRepoTopics(user, repo string, opt ListRepoTopicsOptions) ([]string, error) { +func (c *Client) ListRepoTopics(user, repo string, opt ListRepoTopicsOptions) ([]string, *Response, error) { opt.setDefaults() list := new(topicsList) - err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, list) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/topics?%s", user, repo, opt.getURLQuery().Encode()), nil, nil, list) if err != nil { - return nil, err + return nil, resp, err } - return list.Topics, nil + return list.Topics, resp, nil } // SetRepoTopics replaces the list of repo's topics -func (c *Client) SetRepoTopics(user, repo string, list []string) error { +func (c *Client) SetRepoTopics(user, repo string, list []string) (*Response, error) { l := topicsList{Topics: list} body, err := json.Marshal(&l) if err != nil { - return err + return nil, err } - _, err = c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics", user, repo), jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics", user, repo), jsonHeader, bytes.NewReader(body)) + return resp, err } // AddRepoTopic adds a topic to a repo's topics list -func (c *Client) AddRepoTopic(user, repo, topic string) error { - _, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) - return err +func (c *Client) AddRepoTopic(user, repo, topic string) (*Response, error) { + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) + return resp, err } // DeleteRepoTopic deletes a topic from repo's topics list -func (c *Client) DeleteRepoTopic(user, repo, topic string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) - return err +func (c *Client) DeleteRepoTopic(user, repo, topic string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/topics/%s", user, repo, topic), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_transfer.go b/vendor/code.gitea.io/sdk/gitea/repo_transfer.go index 1b61e2f38f8e..aedb0e52690d 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_transfer.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_transfer.go @@ -19,14 +19,15 @@ type TransferRepoOption struct { } // TransferRepo transfers the ownership of a repository -func (c *Client) TransferRepo(owner, reponame string, opt TransferRepoOption) (*Repository, error) { +func (c *Client) TransferRepo(owner, reponame string, opt TransferRepoOption) (*Repository, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.12.0"); err != nil { - return nil, err + return nil, nil, err } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } repo := new(Repository) - return repo, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/transfer", owner, reponame), jsonHeader, bytes.NewReader(body), repo) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/transfer", owner, reponame), jsonHeader, bytes.NewReader(body), repo) + return repo, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_tree.go b/vendor/code.gitea.io/sdk/gitea/repo_tree.go index d258bdfff282..ce36e460b171 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_tree.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_tree.go @@ -30,11 +30,12 @@ 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) { +func (c *Client) GetTrees(user, repo, ref string, recursive bool) (*GitTreeResponse, *Response, error) { trees := new(GitTreeResponse) var path = fmt.Sprintf("/repos/%s/%s/git/trees/%s", user, repo, ref) if recursive { path += "?recursive=1" } - return trees, c.getParsedResponse("GET", path, nil, nil, trees) + resp, err := c.getParsedResponse("GET", path, nil, nil, trees) + return trees, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/repo_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go index c8ed3a198e82..7358705fe820 100644 --- a/vendor/code.gitea.io/sdk/gitea/repo_watch.go +++ b/vendor/code.gitea.io/sdk/gitea/repo_watch.go @@ -21,53 +21,55 @@ type WatchInfo struct { } // GetWatchedRepos list all the watched repos of user -func (c *Client) GetWatchedRepos(user string) ([]*Repository, error) { +func (c *Client) GetWatchedRepos(user string) ([]*Repository, *Response, error) { repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), nil, nil, &repos) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), nil, nil, &repos) + return repos, resp, err } // GetMyWatchedRepos list repositories watched by the authenticated user -func (c *Client) GetMyWatchedRepos() ([]*Repository, error) { +func (c *Client) GetMyWatchedRepos() ([]*Repository, *Response, error) { repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/user/subscriptions"), nil, nil, &repos) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/subscriptions"), nil, nil, &repos) + return repos, resp, err } // CheckRepoWatch check if the current user is watching a repo -func (c *Client) CheckRepoWatch(repoUser, repoName string) (bool, error) { - status, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) +func (c *Client) CheckRepoWatch(repoUser, repoName string) (bool, *Response, error) { + status, resp, err := c.getStatusCode("GET", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) if err != nil { - return false, err + return false, resp, err } switch status { case http.StatusNotFound: - return false, nil + return false, resp, nil case http.StatusOK: - return true, nil + return true, resp, nil default: - return false, fmt.Errorf("unexpected Status: %d", status) + return false, resp, fmt.Errorf("unexpected Status: %d", status) } } // WatchRepo start to watch a repository -func (c *Client) WatchRepo(repoUser, repoName string) error { - status, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) +func (c *Client) WatchRepo(repoUser, repoName string) (*Response, error) { + status, resp, err := c.getStatusCode("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) if err != nil { - return err + return resp, err } if status == http.StatusOK { - return nil + return resp, nil } - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } // UnWatchRepo stop to watch a repository -func (c *Client) UnWatchRepo(repoUser, repoName string) error { - status, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) +func (c *Client) UnWatchRepo(repoUser, repoName string) (*Response, error) { + status, resp, err := c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), nil, nil) if err != nil { - return err + return resp, err } if status == http.StatusNoContent { - return nil + return resp, nil } - return fmt.Errorf("unexpected Status: %d", status) + return resp, fmt.Errorf("unexpected Status: %d", status) } diff --git a/vendor/code.gitea.io/sdk/gitea/settings.go b/vendor/code.gitea.io/sdk/gitea/settings.go index 1ef1d93785c4..9c39e4e215e1 100644 --- a/vendor/code.gitea.io/sdk/gitea/settings.go +++ b/vendor/code.gitea.io/sdk/gitea/settings.go @@ -32,37 +32,41 @@ type GlobalAttachmentSettings struct { } // GetGlobalUISettings get global ui settings witch are exposed by API -func (c *Client) GetGlobalUISettings() (settings *GlobalUISettings, err error) { +func (c *Client) GetGlobalUISettings() (*GlobalUISettings, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } conf := new(GlobalUISettings) - return conf, c.getParsedResponse("GET", "/settings/ui", jsonHeader, nil, &conf) + resp, err := c.getParsedResponse("GET", "/settings/ui", jsonHeader, nil, &conf) + return conf, resp, err } // GetGlobalRepoSettings get global repository settings witch are exposed by API -func (c *Client) GetGlobalRepoSettings() (settings *GlobalRepoSettings, err error) { +func (c *Client) GetGlobalRepoSettings() (*GlobalRepoSettings, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } conf := new(GlobalRepoSettings) - return conf, c.getParsedResponse("GET", "/settings/repository", jsonHeader, nil, &conf) + resp, err := c.getParsedResponse("GET", "/settings/repository", jsonHeader, nil, &conf) + return conf, resp, err } // GetGlobalAPISettings get global api settings witch are exposed by it -func (c *Client) GetGlobalAPISettings() (settings *GlobalAPISettings, err error) { +func (c *Client) GetGlobalAPISettings() (*GlobalAPISettings, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } conf := new(GlobalAPISettings) - return conf, c.getParsedResponse("GET", "/settings/api", jsonHeader, nil, &conf) + resp, err := c.getParsedResponse("GET", "/settings/api", jsonHeader, nil, &conf) + return conf, resp, err } // GetGlobalAttachmentSettings get global repository settings witch are exposed by API -func (c *Client) GetGlobalAttachmentSettings() (settings *GlobalAttachmentSettings, err error) { +func (c *Client) GetGlobalAttachmentSettings() (*GlobalAttachmentSettings, *Response, error) { if err := c.CheckServerVersionConstraint(">=1.13.0"); err != nil { - return nil, err + return nil, nil, err } conf := new(GlobalAttachmentSettings) - return conf, c.getParsedResponse("GET", "/settings/attachment", jsonHeader, nil, &conf) + resp, err := c.getParsedResponse("GET", "/settings/attachment", jsonHeader, nil, &conf) + return conf, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/status.go b/vendor/code.gitea.io/sdk/gitea/status.go index f072cf89d8a5..7c23b891ed93 100644 --- a/vendor/code.gitea.io/sdk/gitea/status.go +++ b/vendor/code.gitea.io/sdk/gitea/status.go @@ -50,13 +50,14 @@ type CreateStatusOption struct { } // CreateStatus creates a new Status for a given Commit -func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { +func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, *Response, error) { body, err := json.Marshal(&opts) if err != nil { - return nil, err + return nil, nil, err } status := new(Status) - return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), jsonHeader, bytes.NewReader(body), status) + return status, resp, err } // ListStatusesOption options for listing a repository's commit's statuses @@ -65,10 +66,11 @@ type ListStatusesOption struct { } // ListStatuses returns all statuses for a given Commit -func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, error) { +func (c *Client) ListStatuses(owner, repo, sha string, opt ListStatusesOption) ([]*Status, *Response, error) { opt.setDefaults() statuses := make([]*Status, 0, opt.PageSize) - return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?%s", owner, repo, sha, opt.getURLQuery().Encode()), nil, nil, &statuses) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?%s", owner, repo, sha, opt.getURLQuery().Encode()), nil, nil, &statuses) + return statuses, resp, err } // CombinedStatus holds the combined state of several statuses for a single commit @@ -83,7 +85,8 @@ type CombinedStatus struct { } // GetCombinedStatus returns the CombinedStatus for a given Commit -func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { +func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, *Response, error) { status := new(CombinedStatus) - return status, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, sha), nil, nil, status) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/status", owner, repo, sha), nil, nil, status) + return status, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user.go b/vendor/code.gitea.io/sdk/gitea/user.go index 2433474369c9..e909c6861c81 100644 --- a/vendor/code.gitea.io/sdk/gitea/user.go +++ b/vendor/code.gitea.io/sdk/gitea/user.go @@ -29,15 +29,15 @@ type User struct { } // GetUserInfo get user info by user's name -func (c *Client) GetUserInfo(user string) (*User, error) { +func (c *Client) GetUserInfo(user string) (*User, *Response, error) { u := new(User) - err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u) - return u, err + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u) + return u, resp, err } // GetMyUserInfo get user info of current user -func (c *Client) GetMyUserInfo() (*User, error) { +func (c *Client) GetMyUserInfo() (*User, *Response, error) { u := new(User) - err := c.getParsedResponse("GET", "/user", nil, nil, u) - return u, err + resp, err := c.getParsedResponse("GET", "/user", nil, nil, u) + return u, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_app.go b/vendor/code.gitea.io/sdk/gitea/user_app.go index 2205371e68ee..7f7696dc4dcd 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_app.go +++ b/vendor/code.gitea.io/sdk/gitea/user_app.go @@ -9,6 +9,7 @@ import ( "bytes" "encoding/json" "fmt" + "reflect" ) // AccessToken represents an API access token. @@ -25,13 +26,14 @@ type ListAccessTokensOptions struct { } // ListAccessTokens lists all the access tokens of user -func (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, error) { +func (c *Client) ListAccessTokens(opts ListAccessTokensOptions) ([]*AccessToken, *Response, error) { if len(c.username) == 0 { - return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") + return nil, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens?%s", c.username, opts.getURLQuery().Encode()), jsonHeader, nil, &tokens) + return tokens, resp, err } // CreateAccessTokenOption options when create access token @@ -40,23 +42,39 @@ type CreateAccessTokenOption struct { } // CreateAccessToken create one access token with options -func (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, error) { +func (c *Client) CreateAccessToken(opt CreateAccessTokenOption) (*AccessToken, *Response, error) { if len(c.username) == 0 { - return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") + return nil, nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") } body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } t := new(AccessToken) - return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", c.username), jsonHeader, bytes.NewReader(body), t) + resp, err := c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", c.username), jsonHeader, bytes.NewReader(body), t) + return t, resp, err } -// DeleteAccessToken delete token with key id -func (c *Client) DeleteAccessToken(keyID int64) error { +// DeleteAccessToken delete token, identified by ID and if not available by name +func (c *Client) DeleteAccessToken(value interface{}) (*Response, error) { if len(c.username) == 0 { - return fmt.Errorf("\"username\" not set: only BasicAuth allowed") + return nil, fmt.Errorf("\"username\" not set: only BasicAuth allowed") } - _, err := c.getResponse("DELETE", fmt.Sprintf("/users/%s/tokens/%d", c.username, keyID), jsonHeader, nil) - return err + + var token = "" + + switch reflect.ValueOf(value).Kind() { + case reflect.Int64: + token = fmt.Sprintf("%d", value.(int64)) + case reflect.String: + if err := c.CheckServerVersionConstraint(">= 1.13.0"); err != nil { + return nil, err + } + token = value.(string) + default: + return nil, fmt.Errorf("only string and int64 supported") + } + + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/users/%s/tokens/%s", c.username, token), jsonHeader, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_email.go b/vendor/code.gitea.io/sdk/gitea/user_email.go index 5cb4721f63b5..4962b082b407 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_email.go +++ b/vendor/code.gitea.io/sdk/gitea/user_email.go @@ -23,10 +23,11 @@ type ListEmailsOptions struct { } // ListEmails all the email addresses of user -func (c *Client) ListEmails(opt ListEmailsOptions) ([]*Email, error) { +func (c *Client) ListEmails(opt ListEmailsOptions) ([]*Email, *Response, error) { opt.setDefaults() emails := make([]*Email, 0, opt.PageSize) - return emails, c.getParsedResponse("GET", fmt.Sprintf("/user/emails?%s", opt.getURLQuery().Encode()), nil, nil, &emails) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/emails?%s", opt.getURLQuery().Encode()), nil, nil, &emails) + return emails, resp, err } // CreateEmailOption options when creating email addresses @@ -36,13 +37,14 @@ type CreateEmailOption struct { } // AddEmail add one email to current user with options -func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, error) { +func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } emails := make([]*Email, 0, 3) - return emails, c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), &emails) + resp, err := c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), &emails) + return emails, resp, err } // DeleteEmailOption options when deleting email addresses @@ -52,11 +54,11 @@ type DeleteEmailOption struct { } // DeleteEmail delete one email of current users' -func (c *Client) DeleteEmail(opt DeleteEmailOption) error { +func (c *Client) DeleteEmail(opt DeleteEmailOption) (*Response, error) { body, err := json.Marshal(&opt) if err != nil { - return err + return nil, err } - _, err = c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body)) - return err + _, resp, err := c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body)) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_follow.go b/vendor/code.gitea.io/sdk/gitea/user_follow.go index fdc53eff8053..c8bafc01e5e3 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_follow.go +++ b/vendor/code.gitea.io/sdk/gitea/user_follow.go @@ -12,17 +12,19 @@ type ListFollowersOptions struct { } // ListMyFollowers list all the followers of current user -func (c *Client) ListMyFollowers(opt ListFollowersOptions) ([]*User, error) { +func (c *Client) ListMyFollowers(opt ListFollowersOptions) ([]*User, *Response, error) { opt.setDefaults() users := make([]*User, 0, opt.PageSize) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?%s", opt.getURLQuery().Encode()), nil, nil, &users) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/followers?%s", opt.getURLQuery().Encode()), nil, nil, &users) + return users, resp, err } // ListFollowers list all the followers of one user -func (c *Client) ListFollowers(user string, opt ListFollowersOptions) ([]*User, error) { +func (c *Client) ListFollowers(user string, opt ListFollowersOptions) ([]*User, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?%s", user, opt.getURLQuery().Encode()), nil, nil, &users) + return users, resp, err } // ListFollowingOptions options for listing a user's users being followed @@ -31,39 +33,41 @@ type ListFollowingOptions struct { } // ListMyFollowing list all the users current user followed -func (c *Client) ListMyFollowing(opt ListFollowingOptions) ([]*User, error) { +func (c *Client) ListMyFollowing(opt ListFollowingOptions) ([]*User, *Response, error) { opt.setDefaults() users := make([]*User, 0, opt.PageSize) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?%s", opt.getURLQuery().Encode()), nil, nil, &users) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/following?%s", opt.getURLQuery().Encode()), nil, nil, &users) + return users, resp, err } // ListFollowing list all the users the user followed -func (c *Client) ListFollowing(user string, opt ListFollowingOptions) ([]*User, error) { +func (c *Client) ListFollowing(user string, opt ListFollowingOptions) ([]*User, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?%s", user, opt.getURLQuery().Encode()), nil, nil, &users) + return users, resp, err } // IsFollowing if current user followed the target -func (c *Client) IsFollowing(target string) bool { - _, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil) - return err == nil +func (c *Client) IsFollowing(target string) (bool, *Response) { + _, resp, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil) + return err == nil, resp } // IsUserFollowing if the user followed the target -func (c *Client) IsUserFollowing(user, target string) bool { - _, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil) - return err == nil +func (c *Client) IsUserFollowing(user, target string) (bool, *Response) { + _, resp, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil) + return err == nil, resp } // Follow set current user follow the target -func (c *Client) Follow(target string) error { - _, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil) - return err +func (c *Client) Follow(target string) (*Response, error) { + _, resp, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil) + return resp, err } // Unfollow set current user unfollow the target -func (c *Client) Unfollow(target string) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil) - return err +func (c *Client) Unfollow(target string) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go index 026cb1ae8cae..d3d64b41e464 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go +++ b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go @@ -39,23 +39,26 @@ type ListGPGKeysOptions struct { } // ListGPGKeys list all the GPG keys of the user -func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, error) { +func (c *Client) ListGPGKeys(user string, opt ListGPGKeysOptions) ([]*GPGKey, *Response, error) { opt.setDefaults() keys := make([]*GPGKey, 0, opt.PageSize) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) + return keys, resp, err } // ListMyGPGKeys list all the GPG keys of current user -func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, error) { +func (c *Client) ListMyGPGKeys(opt *ListGPGKeysOptions) ([]*GPGKey, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys) + return keys, resp, err } // GetGPGKey get current user's GPG key by key id -func (c *Client) GetGPGKey(keyID int64) (*GPGKey, error) { +func (c *Client) GetGPGKey(keyID int64) (*GPGKey, *Response, error) { key := new(GPGKey) - return key, c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil, &key) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil, &key) + return key, resp, err } // CreateGPGKeyOption options create user GPG key @@ -66,17 +69,18 @@ type CreateGPGKeyOption struct { } // CreateGPGKey create GPG key with options -func (c *Client) CreateGPGKey(opt CreateGPGKeyOption) (*GPGKey, error) { +func (c *Client) CreateGPGKey(opt CreateGPGKeyOption) (*GPGKey, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } key := new(GPGKey) - return key, c.getParsedResponse("POST", "/user/gpg_keys", jsonHeader, bytes.NewReader(body), key) + resp, err := c.getParsedResponse("POST", "/user/gpg_keys", jsonHeader, bytes.NewReader(body), key) + return key, resp, err } // DeleteGPGKey delete GPG key with key id -func (c *Client) DeleteGPGKey(keyID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil) - return err +func (c *Client) DeleteGPGKey(keyID int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/gpg_keys/%d", keyID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_key.go b/vendor/code.gitea.io/sdk/gitea/user_key.go index 6c71487585df..d005f00bef58 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_key.go +++ b/vendor/code.gitea.io/sdk/gitea/user_key.go @@ -30,23 +30,26 @@ type ListPublicKeysOptions struct { } // ListPublicKeys list all the public keys of the user -func (c *Client) ListPublicKeys(user string, opt ListPublicKeysOptions) ([]*PublicKey, error) { +func (c *Client) ListPublicKeys(user string, opt ListPublicKeysOptions) ([]*PublicKey, *Response, error) { opt.setDefaults() keys := make([]*PublicKey, 0, opt.PageSize) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys?%s", user, opt.getURLQuery().Encode()), nil, nil, &keys) + return keys, resp, err } // ListMyPublicKeys list all the public keys of current user -func (c *Client) ListMyPublicKeys(opt ListPublicKeysOptions) ([]*PublicKey, error) { +func (c *Client) ListMyPublicKeys(opt ListPublicKeysOptions) ([]*PublicKey, *Response, 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) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/keys?%s", opt.getURLQuery().Encode()), nil, nil, &keys) + return keys, resp, err } // GetPublicKey get current user's public key by key id -func (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) { +func (c *Client) GetPublicKey(keyID int64) (*PublicKey, *Response, error) { key := new(PublicKey) - return key, c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key) + return key, resp, err } // CreateKeyOption options when creating a key @@ -60,17 +63,18 @@ type CreateKeyOption struct { } // CreatePublicKey create public key with options -func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) { +func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, *Response, error) { body, err := json.Marshal(&opt) if err != nil { - return nil, err + return nil, nil, err } key := new(PublicKey) - return key, c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key) + resp, err := c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key) + return key, resp, err } // DeletePublicKey delete public key with key id -func (c *Client) DeletePublicKey(keyID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil) - return err +func (c *Client) DeletePublicKey(keyID int64) (*Response, error) { + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil) + return resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/user_search.go b/vendor/code.gitea.io/sdk/gitea/user_search.go index 5e098211fb53..7e4064d18e9b 100644 --- a/vendor/code.gitea.io/sdk/gitea/user_search.go +++ b/vendor/code.gitea.io/sdk/gitea/user_search.go @@ -35,10 +35,10 @@ func (opt *SearchUsersOption) QueryEncode() string { } // SearchUsers finds users by query -func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, error) { +func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, *Response, error) { link, _ := url.Parse("/users/search") link.RawQuery = opt.QueryEncode() - resp := new(searchUsersResponse) - err := c.getParsedResponse("GET", link.String(), nil, nil, &resp) - return resp.Users, err + userResp := new(searchUsersResponse) + resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &userResp) + return userResp.Users, resp, err } diff --git a/vendor/code.gitea.io/sdk/gitea/version.go b/vendor/code.gitea.io/sdk/gitea/version.go index b0f1c7b09e83..57c64dc4107f 100644 --- a/vendor/code.gitea.io/sdk/gitea/version.go +++ b/vendor/code.gitea.io/sdk/gitea/version.go @@ -11,11 +11,12 @@ import ( ) // ServerVersion returns the version of the server -func (c *Client) ServerVersion() (string, error) { +func (c *Client) ServerVersion() (string, *Response, error) { var v = struct { Version string `json:"version"` }{} - return v.Version, c.getParsedResponse("GET", "/version", nil, nil, &v) + resp, err := c.getParsedResponse("GET", "/version", nil, nil, &v) + return v.Version, resp, err } // CheckServerVersionConstraint validates that the login's server satisfies a @@ -46,7 +47,7 @@ func (c *Client) loadClientServerVersion() error { c.versionLock.Lock() defer c.versionLock.Unlock() - raw, err := c.ServerVersion() + raw, _, err := c.ServerVersion() if err != nil { return err } diff --git a/vendor/modules.txt b/vendor/modules.txt index b1c6a373a7c3..dfd64a859a3e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,7 +4,7 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks -# code.gitea.io/sdk/gitea v0.12.1-0.20200907221938-87f7b1866d63 +# code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd ## explicit code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0 @@ -429,7 +429,7 @@ github.com/hashicorp/go-cleanhttp # github.com/hashicorp/go-retryablehttp v0.6.7 ## explicit github.com/hashicorp/go-retryablehttp -# github.com/hashicorp/go-version v1.2.0 => github.com/6543/go-version v1.2.3 +# github.com/hashicorp/go-version v1.2.1 => github.com/6543/go-version v1.2.3 ## explicit github.com/hashicorp/go-version # github.com/hashicorp/hcl v1.0.0 From d1ff7296b75099a14fe3de8b2bb85c25bc99d78e Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 18:38:54 +0200 Subject: [PATCH 28/46] adapt new sdk --- modules/migrations/gitea_downloader.go | 29 +++++++++++++------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index cc223bf9dca7..b9bbbbbb0740 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -122,7 +122,7 @@ func (g *GiteaDownloader) GetRepoInfo() (*base.Repository, error) { return nil, errors.New("error: GiteaDownloader is nil") } - repo, err := g.client.GetRepo(g.repoOwner, g.repoName) + repo, _, err := g.client.GetRepo(g.repoOwner, g.repoName) if err != nil { return nil, err } @@ -139,7 +139,8 @@ func (g *GiteaDownloader) GetRepoInfo() (*base.Repository, error) { // GetTopics return gitea topics func (g *GiteaDownloader) GetTopics() ([]string, error) { - return g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea_sdk.ListRepoTopicsOptions{}) + topics, _, err := g.client.ListRepoTopics(g.repoOwner, g.repoName, gitea_sdk.ListRepoTopicsOptions{}) + return topics, err } // GetMilestones returns milestones @@ -154,7 +155,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { default: } - ms, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea_sdk.ListMilestoneOption{ + ms, _, err := g.client.ListRepoMilestones(g.repoOwner, g.repoName, gitea_sdk.ListMilestoneOption{ ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, @@ -212,7 +213,7 @@ func (g *GiteaDownloader) GetLabels() ([]*base.Label, error) { default: } - ls, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea_sdk.ListLabelsOptions{ListOptions: gitea_sdk.ListOptions{ + ls, _, err := g.client.ListRepoLabels(g.repoOwner, g.repoName, gitea_sdk.ListLabelsOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, }}) @@ -272,7 +273,7 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { default: } - rl, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea_sdk.ListReleasesOptions{ListOptions: gitea_sdk.ListOptions{ + rl, _, err := g.client.ListReleases(g.repoOwner, g.repoName, gitea_sdk.ListReleasesOptions{ListOptions: gitea_sdk.ListOptions{ PageSize: g.maxPerPage, Page: i, }}) @@ -292,7 +293,7 @@ func (g *GiteaDownloader) GetReleases() ([]*base.Release, error) { // GetAsset returns an asset func (g *GiteaDownloader) GetAsset(_ string, relID, id int64) (io.ReadCloser, error) { - asset, err := g.client.GetReleaseAttachment(g.repoOwner, g.repoName, relID, id) + asset, _, err := g.client.GetReleaseAttachment(g.repoOwner, g.repoName, relID, id) if err != nil { return nil, err } @@ -311,7 +312,7 @@ func (g *GiteaDownloader) getIssueReactions(index int64) ([]*base.Reaction, erro log.Info("GiteaDownloader: instance to old, skip getIssueReactions") return reactions, nil } - rl, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) + rl, _, err := g.client.GetIssueReactions(g.repoOwner, g.repoName, index) if err != nil { return nil, err } @@ -332,7 +333,7 @@ func (g *GiteaDownloader) getCommentReactions(commentID int64) ([]*base.Reaction log.Info("GiteaDownloader: instance to old, skip getCommentReactions") return reactions, nil } - rl, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, commentID) + rl, _, err := g.client.GetIssueCommentReactions(g.repoOwner, g.repoName, commentID) if err != nil { return nil, err } @@ -354,7 +355,7 @@ func (g *GiteaDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, err } var allIssues = make([]*base.Issue, 0, perPage) - issues, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea_sdk.ListIssueOption{ + issues, _, err := g.client.ListRepoIssues(g.repoOwner, g.repoName, gitea_sdk.ListIssueOption{ ListOptions: gitea_sdk.ListOptions{Page: page, PageSize: perPage}, State: gitea_sdk.StateAll, Type: gitea_sdk.IssueTypeIssue, @@ -422,7 +423,7 @@ func (g *GiteaDownloader) GetComments(index int64) ([]*base.Comment, error) { default: } - comments, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea_sdk.ListIssueCommentOptions{ListOptions: gitea_sdk.ListOptions{ + comments, _, err := g.client.ListIssueComments(g.repoOwner, g.repoName, index, gitea_sdk.ListIssueCommentOptions{ListOptions: gitea_sdk.ListOptions{ // PageSize: g.maxPerPage, // Page: i, }}) @@ -463,7 +464,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques } var allPRs = make([]*base.PullRequest, 0, perPage) - prs, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea_sdk.ListPullRequestsOptions{ + prs, _, err := g.client.ListRepoPullRequests(g.repoOwner, g.repoName, gitea_sdk.ListPullRequestsOptions{ ListOptions: gitea_sdk.ListOptions{ Page: page, PageSize: perPage, @@ -500,7 +501,7 @@ func (g *GiteaDownloader) GetPullRequests(page, perPage int) ([]*base.PullReques headSHA = pr.Head.Sha headRef = pr.Head.Ref if headSHA == "" { - headCommit, err := g.client.GetSingleCommit(g.repoOwner, g.repoName, url.PathEscape(pr.Head.Ref)) + headCommit, _, err := g.client.GetSingleCommit(g.repoOwner, g.repoName, url.PathEscape(pr.Head.Ref)) if err != nil { return nil, false, fmt.Errorf("error while resolving git ref: %v", err) } @@ -597,7 +598,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { default: } - prl, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea_sdk.ListPullReviewsOptions{ListOptions: gitea_sdk.ListOptions{ + prl, _, err := g.client.ListPullReviews(g.repoOwner, g.repoName, index, gitea_sdk.ListPullReviewsOptions{ListOptions: gitea_sdk.ListOptions{ Page: i, PageSize: g.maxPerPage, }}) @@ -607,7 +608,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { for _, pr := range prl { - rcl, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID) + rcl, _, err := g.client.ListPullReviewComments(g.repoOwner, g.repoName, index, pr.ID) if err != nil { return nil, err } From ee34d41449788c2d0ec562c6ceb8c2b86d75daf6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 18:47:41 +0200 Subject: [PATCH 29/46] adopt new features --- modules/migrations/gitea_downloader.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index b9bbbbbb0740..998dfc50f4fd 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -96,10 +96,14 @@ func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, passwo paginationSupport = false } - // set small maxPerPage since we can only guess (default would be 50 but this can differ) - // safest value would be 1 but this is really inefficient - // TODO https://github.com/go-gitea/gitea/issues/12664 + // set small maxPerPage since we can only guess + // (default would be 50 but this can differ) maxPerPage := 10 + // new gitea instances can tell us what maximum they have + apiConf, _, err := giteaClient.GetGlobalAPISettings() + if err == nil { + maxPerPage = apiConf.MaxResponseItems + } return &GiteaDownloader{ ctx: ctx, @@ -167,8 +171,7 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { } for i := range ms { - // TODO: expose this info - // https://github.com/go-gitea/gitea/issues/12655 + // old gitea instances dont have this information createdAT := time.Now() var updatedAT *time.Time if ms[i].Closed != nil { @@ -176,6 +179,14 @@ func (g *GiteaDownloader) GetMilestones() ([]*base.Milestone, error) { updatedAT = ms[i].Closed } + // new gitea instances (>=1.13) do + if !ms[i].Created.IsZero() { + createdAT = ms[i].Created + } + if ms[i].Updated != nil && !ms[i].Updated.IsZero() { + updatedAT = ms[i].Updated + } + milestones = append(milestones, &base.Milestone{ Title: ms[i].Title, Description: ms[i].Description, From 9001eebe750aa9580a389dae454f756678a85be9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 18:52:46 +0200 Subject: [PATCH 30/46] check version before err --- modules/migrations/gitea_downloader.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 998dfc50f4fd..f8518ef139f2 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -100,8 +100,11 @@ func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, passwo // (default would be 50 but this can differ) maxPerPage := 10 // new gitea instances can tell us what maximum they have - apiConf, _, err := giteaClient.GetGlobalAPISettings() - if err == nil { + if giteaClient.CheckServerVersionConstraint(">=1.13.0") == nil { + apiConf, _, err := giteaClient.GetGlobalAPISettings() + if err != nil { + return nil, err + } maxPerPage = apiConf.MaxResponseItems } From a26606fb074f9dfedab5ecd71b2c0d3847dd0bf5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 23:08:36 +0200 Subject: [PATCH 31/46] adapt: 'migrate service type switch page' --- options/locale/locale_en-US.ini | 1 + public/img/svg/gitea-gitea.svg | 1 + templates/repo/migrate/gitea.tmpl | 137 ++++++++++++++++++++++++++++++ web_src/svg/gitea-gitea.svg | 36 ++++++++ 4 files changed, 175 insertions(+) create mode 100644 public/img/svg/gitea-gitea.svg create mode 100644 templates/repo/migrate/gitea.tmpl create mode 100644 web_src/svg/gitea-gitea.svg diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 4430c48802a1..ceda09224366 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -740,6 +740,7 @@ migrate.migrating_failed = Migrating from %s failed. migrate.github.description = Migrating data from Github.com or Github Enterprise. migrate.git.description = Migrating or Mirroring git data from Git services migrate.gitlab.description = Migrating data from GitLab.com or Self-Hosted gitlab server. +migrate.gitea.description = Migrating data from Gitea.com or Self-Hosted Gitea server. mirror_from = mirror of forked_from = forked from diff --git a/public/img/svg/gitea-gitea.svg b/public/img/svg/gitea-gitea.svg new file mode 100644 index 000000000000..61a9d677aacb --- /dev/null +++ b/public/img/svg/gitea-gitea.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl new file mode 100644 index 000000000000..23d231fe9989 --- /dev/null +++ b/templates/repo/migrate/gitea.tmpl @@ -0,0 +1,137 @@ +{{template "base/head" .}} +
+
+
+
+ {{.CsrfTokenHtml}} +

+ {{.i18n.Tr "repo.migrate.migrate" .service.Title}} + +

+
+ {{template "base/alert" .}} +
+ + + + {{.i18n.Tr "repo.migrate.clone_address_desc"}}{{if .ContextUser.CanImportLocal}} {{.i18n.Tr "repo.migrate.clone_local_path"}}{{end}} + {{if .LFSActive}}
{{.i18n.Tr "repo.migrate.lfs_mirror_unsupported"}}{{end}} +
+
+ +
+ + + {{svg "octicon-question"}} +
+ +
+ +
+ {{if .DisableMirrors}} + + + {{else}} + + + {{end}} +
+
+ + {{.i18n.Tr "repo.migrate.migrate_items_options"}} +
+
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+ + +
+
+
+ +
+ +
+ + +
+ +
+ + +
+
+ +
+ {{if .IsForcedPrivate}} + + + {{else}} + + + {{end}} +
+
+
+ + +
+ +
+ + + {{.i18n.Tr "cancel"}} +
+
+
+
+
+
+{{template "base/footer" .}} diff --git a/web_src/svg/gitea-gitea.svg b/web_src/svg/gitea-gitea.svg new file mode 100644 index 000000000000..cb7ae8384c6b --- /dev/null +++ b/web_src/svg/gitea-gitea.svg @@ -0,0 +1,36 @@ + + + + + + image/svg+xml + + + + + + + + + + From 878df2cbb3291258bafe012d5923c6ef8973363a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 14 Sep 2020 23:40:18 +0200 Subject: [PATCH 32/46] optimize --- public/img/svg/gitea-gitea.svg | 2 +- web_src/svg/gitea-gitea.svg | 37 +--------------------------------- 2 files changed, 2 insertions(+), 37 deletions(-) diff --git a/public/img/svg/gitea-gitea.svg b/public/img/svg/gitea-gitea.svg index 61a9d677aacb..7ccd7973a77b 100644 --- a/public/img/svg/gitea-gitea.svg +++ b/public/img/svg/gitea-gitea.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/web_src/svg/gitea-gitea.svg b/web_src/svg/gitea-gitea.svg index cb7ae8384c6b..e2762af51ba3 100644 --- a/web_src/svg/gitea-gitea.svg +++ b/web_src/svg/gitea-gitea.svg @@ -1,36 +1 @@ - - - - - - image/svg+xml - - - - - - - - - - + \ No newline at end of file From ddee989423792f0f03f3c570c91e67a50f9856ad Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 00:55:04 +0200 Subject: [PATCH 33/46] Fix DefaultBranch --- modules/migrations/base/repo.go | 15 ++++++++------- modules/migrations/gitea_downloader.go | 13 +++++++------ modules/migrations/gitea_uploader.go | 1 + modules/migrations/github.go | 18 ++++++++++++------ modules/migrations/gitlab.go | 13 +++++++------ modules/repository/repo.go | 11 ++++++----- 6 files changed, 41 insertions(+), 30 deletions(-) diff --git a/modules/migrations/base/repo.go b/modules/migrations/base/repo.go index 764c9e8d8602..d26a9118545d 100644 --- a/modules/migrations/base/repo.go +++ b/modules/migrations/base/repo.go @@ -7,11 +7,12 @@ package base // Repository defines a standard repository information type Repository struct { - Name string - Owner string - IsPrivate bool - IsMirror bool - Description string - CloneURL string - OriginalURL string + Name string + Owner string + IsPrivate bool + IsMirror bool + Description string + CloneURL string + OriginalURL string + DefaultBranch string } diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index f8518ef139f2..f1640894d063 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -135,12 +135,13 @@ func (g *GiteaDownloader) GetRepoInfo() (*base.Repository, error) { } return &base.Repository{ - Name: repo.Name, - Owner: repo.Owner.UserName, - IsPrivate: repo.Private, - Description: repo.Description, - CloneURL: repo.CloneURL, - OriginalURL: repo.HTMLURL, + Name: repo.Name, + Owner: repo.Owner.UserName, + IsPrivate: repo.Private, + Description: repo.Description, + CloneURL: repo.CloneURL, + OriginalURL: repo.HTMLURL, + DefaultBranch: repo.DefaultBranch, }, nil } diff --git a/modules/migrations/gitea_uploader.go b/modules/migrations/gitea_uploader.go index 8d9951a9b13a..cd1fd5cb8d8e 100644 --- a/modules/migrations/gitea_uploader.go +++ b/modules/migrations/gitea_uploader.go @@ -122,6 +122,7 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate if err != nil { return err } + r.DefaultBranch = repo.DefaultBranch r, err = repository.MigrateRepositoryGitData(g.doer, owner, r, base.MigrateOptions{ RepoName: g.repoName, diff --git a/modules/migrations/github.go b/modules/migrations/github.go index dca6b4ba7278..e300904e4b3e 100644 --- a/modules/migrations/github.go +++ b/modules/migrations/github.go @@ -143,14 +143,20 @@ func (g *GithubDownloaderV3) GetRepoInfo() (*base.Repository, error) { } g.rate = &resp.Rate + defaultBranch := "master" + if gr.DefaultBranch != nil { + defaultBranch = *gr.DefaultBranch + } + // convert github repo to stand Repo return &base.Repository{ - Owner: g.repoOwner, - Name: gr.GetName(), - IsPrivate: *gr.Private, - Description: gr.GetDescription(), - OriginalURL: gr.GetHTMLURL(), - CloneURL: gr.GetCloneURL(), + Owner: g.repoOwner, + Name: gr.GetName(), + IsPrivate: *gr.Private, + Description: gr.GetDescription(), + OriginalURL: gr.GetHTMLURL(), + CloneURL: gr.GetCloneURL(), + DefaultBranch: defaultBranch, }, nil } diff --git a/modules/migrations/gitlab.go b/modules/migrations/gitlab.go index 50ed42b1c430..3aa63d6f55e2 100644 --- a/modules/migrations/gitlab.go +++ b/modules/migrations/gitlab.go @@ -139,12 +139,13 @@ func (g *GitlabDownloader) GetRepoInfo() (*base.Repository, error) { // convert gitlab repo to stand Repo return &base.Repository{ - Owner: owner, - Name: gr.Name, - IsPrivate: private, - Description: gr.Description, - OriginalURL: gr.WebURL, - CloneURL: gr.HTTPURLToRepo, + Owner: owner, + Name: gr.Name, + IsPrivate: private, + Description: gr.Description, + OriginalURL: gr.WebURL, + CloneURL: gr.HTTPURLToRepo, + DefaultBranch: gr.DefaultBranch, }, nil } diff --git a/modules/repository/repo.go b/modules/repository/repo.go index 36e9ed49c16b..f63ae1cdf087 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -102,18 +102,19 @@ func MigrateRepositoryGitData(doer, u *models.User, repo *models.Repository, opt return repo, fmt.Errorf("git.IsEmpty: %v", err) } - if !opts.Releases && !repo.IsEmpty { + if !repo.IsEmpty { // Try to get HEAD branch and set it as default branch. headBranch, err := gitRepo.GetHEADBranch() if err != nil { return repo, fmt.Errorf("GetHEADBranch: %v", err) } - if headBranch != nil { + if headBranch != nil && len(repo.DefaultBranch) == 0 { repo.DefaultBranch = headBranch.Name } - - if err = SyncReleasesWithTags(repo, gitRepo); err != nil { - log.Error("Failed to synchronize tags to releases for repository: %v", err) + if !opts.Releases { + if err = SyncReleasesWithTags(repo, gitRepo); err != nil { + log.Error("Failed to synchronize tags to releases for repository: %v", err) + } } } From 17a8cc07143dc5942a1a03afddfbbb512ae1b779 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 01:06:03 +0200 Subject: [PATCH 34/46] impruve --- modules/repository/repo.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/modules/repository/repo.go b/modules/repository/repo.go index f63ae1cdf087..b18dfddd2e5a 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -103,14 +103,17 @@ func MigrateRepositoryGitData(doer, u *models.User, repo *models.Repository, opt } if !repo.IsEmpty { - // Try to get HEAD branch and set it as default branch. - headBranch, err := gitRepo.GetHEADBranch() - if err != nil { - return repo, fmt.Errorf("GetHEADBranch: %v", err) - } - if headBranch != nil && len(repo.DefaultBranch) == 0 { - repo.DefaultBranch = headBranch.Name + if len(repo.DefaultBranch) == 0 { + // Try to get HEAD branch and set it as default branch. + headBranch, err := gitRepo.GetHEADBranch() + if err != nil { + return repo, fmt.Errorf("GetHEADBranch: %v", err) + } + if headBranch != nil { + repo.DefaultBranch = headBranch.Name + } } + if !opts.Releases { if err = SyncReleasesWithTags(repo, gitRepo); err != nil { log.Error("Failed to synchronize tags to releases for repository: %v", err) From b4b6ce3eb071a73ae1c777ae7303acd21fbc6073 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 02:09:58 +0200 Subject: [PATCH 35/46] handle subPath --- modules/migrations/gitea_downloader.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index f1640894d063..6cf0f19dd6e6 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -50,8 +50,11 @@ func (f *GiteaDownloaderFactory) New(ctx context.Context, opts base.MigrateOptio return nil, fmt.Errorf("invalid path") } - //TODO handle gitea installed in subpath ... - repoPath := repoNameSpace + repoPath := strings.Join(path[len(path)-2:], "/") + if len(path) > 2 { + subPath := strings.Join(path[:len(path)-2], "/") + baseURL += "/" + subPath + } log.Trace("Create gitea downloader. BaseURL: %s RepoName: %s", baseURL, repoNameSpace) From 3dea64a225758f491a1028f9f5264c281608ca51 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 02:25:46 +0200 Subject: [PATCH 36/46] fix test --- modules/migrations/gitea_downloader_test.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 2babf29e9110..2467cb69603d 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -64,12 +64,13 @@ func TestGiteaDownloadRepo(t *testing.T) { repo, err := downloader.GetRepoInfo() assert.NoError(t, err) assert.EqualValues(t, &base.Repository{ - Name: "test_repo", - Owner: "gitea", - IsPrivate: false, // TODO: set test repo private - Description: "Test repository for testing migration from gitea to gitea", - CloneURL: "https://gitea.com/gitea/test_repo.git", - OriginalURL: "https://gitea.com/gitea/test_repo", + Name: "test_repo", + Owner: "gitea", + IsPrivate: false, + Description: "Test repository for testing migration from gitea to gitea", + CloneURL: "https://gitea.com/gitea/test_repo.git", + OriginalURL: "https://gitea.com/gitea/test_repo", + DefaultBranch: "master", }, repo) topics, err := downloader.GetTopics() From 599b8feaf7e3816a3ca1d95e69f045b67146b58a Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 04:16:08 +0200 Subject: [PATCH 37/46] Fix ReviewCommentPosition --- modules/migrations/gitea_downloader.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index 6cf0f19dd6e6..f00d6cdbfac7 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -642,7 +642,7 @@ func (g *GiteaDownloader) GetReviews(index int64) ([]*base.Review, error) { Content: rcl[i].Body, TreePath: rcl[i].Path, DiffHunk: rcl[i].DiffHunk, - Position: line, + Line: line, CommitID: rcl[i].CommitID, PosterID: rcl[i].Reviewer.ID, CreatedAt: rcl[i].Created, From beb2c25e3a6d3b05d174ca9eab7eab9b055df8e4 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 05:21:06 +0200 Subject: [PATCH 38/46] test GetReviews --- modules/migrations/gitea_downloader_test.go | 40 ++++++++++++++++++--- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/modules/migrations/gitea_downloader_test.go b/modules/migrations/gitea_downloader_test.go index 2467cb69603d..c52c1225f401 100644 --- a/modules/migrations/gitea_downloader_test.go +++ b/modules/migrations/gitea_downloader_test.go @@ -296,6 +296,41 @@ func TestGiteaDownloadRepo(t *testing.T) { MergeCommitSHA: "827aa28a907853e5ddfa40c8f9bc52471a2685fd", PatchURL: "https://gitea.com/gitea/test_repo/pulls/12.patch", }, prs[1]) + + reviews, err := downloader.GetReviews(7) + assert.NoError(t, err) + if assert.Len(t, reviews, 3) { + assert.EqualValues(t, 689, reviews[0].ReviewerID) + assert.EqualValues(t, "6543", reviews[0].ReviewerName) + assert.EqualValues(t, "techknowlogick", reviews[1].ReviewerName) + assert.EqualValues(t, "techknowlogick", reviews[2].ReviewerName) + assert.False(t, reviews[1].Official) + assert.EqualValues(t, "I think this needs some changes", reviews[1].Content) + assert.EqualValues(t, "REQUEST_CHANGES", reviews[1].State) + assert.True(t, reviews[2].Official) + assert.EqualValues(t, "looks good", reviews[2].Content) + assert.EqualValues(t, "APPROVED", reviews[2].State) + + // TODO: https://github.com/go-gitea/gitea/issues/12846 + // assert.EqualValues(t, 9, reviews[1].ReviewerID) + // assert.EqualValues(t, 9, reviews[2].ReviewerID) + + assert.Len(t, reviews[0].Comments, 1) + assert.EqualValues(t, &base.ReviewComment{ + ID: 116561, + InReplyTo: 0, + Content: "is one `\\newline` to less?", + TreePath: "README.md", + DiffHunk: "@@ -2,3 +2,3 @@\n \n-Test repository for testing migration from gitea 2 gitea\n\\ No newline at end of file\n+Test repository for testing migration from gitea 2 gitea", + Position: 0, + Line: 4, + CommitID: "187ece0cb6631e2858a6872e5733433bb3ca3b03", + PosterID: 689, + Reactions: nil, + CreatedAt: time.Date(2020, 9, 1, 16, 12, 58, 0, time.UTC), + UpdatedAt: time.Date(2020, 9, 1, 16, 12, 58, 0, time.UTC), + }, reviews[0].Comments[0]) + } } func assertEqualPulls(t *testing.T, pullExp, pullGet *base.PullRequest) { @@ -328,8 +363,3 @@ func pull2issue(pull *base.PullRequest) *base.Issue { Assignees: pull.Assignees, } } - -/* - ToDo: - GetReviews(pullRequestNumber int64) ([]*Review, error) -*/ From 2b5c3004a2e7b09ddc9cc2f3ba95c29a0378e2e3 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 02:22:12 +0200 Subject: [PATCH 39/46] add DefaultBranch int test set --- modules/migrations/github_test.go | 11 ++++++----- modules/migrations/gitlab_test.go | 11 ++++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/modules/migrations/github_test.go b/modules/migrations/github_test.go index e0349239bc2d..0a585c4ead7c 100644 --- a/modules/migrations/github_test.go +++ b/modules/migrations/github_test.go @@ -72,11 +72,12 @@ func TestGitHubDownloadRepo(t *testing.T) { repo, err := downloader.GetRepoInfo() assert.NoError(t, err) assert.EqualValues(t, &base.Repository{ - Name: "test_repo", - Owner: "go-gitea", - Description: "Test repository for testing migration from github to gitea", - CloneURL: "https://github.com/go-gitea/test_repo.git", - OriginalURL: "https://github.com/go-gitea/test_repo", + Name: "test_repo", + Owner: "go-gitea", + Description: "Test repository for testing migration from github to gitea", + CloneURL: "https://github.com/go-gitea/test_repo.git", + OriginalURL: "https://github.com/go-gitea/test_repo", + DefaultBranch: "master", }, repo) topics, err := downloader.GetTopics() diff --git a/modules/migrations/gitlab_test.go b/modules/migrations/gitlab_test.go index dd455bd674c8..f64d72147cf5 100644 --- a/modules/migrations/gitlab_test.go +++ b/modules/migrations/gitlab_test.go @@ -37,11 +37,12 @@ func TestGitlabDownloadRepo(t *testing.T) { assert.NoError(t, err) // Repo Owner is blank in Gitlab Group repos assert.EqualValues(t, &base.Repository{ - Name: "test_repo", - Owner: "", - Description: "Test repository for testing migration from gitlab to gitea", - CloneURL: "https://gitlab.com/gitea/test_repo.git", - OriginalURL: "https://gitlab.com/gitea/test_repo", + Name: "test_repo", + Owner: "", + Description: "Test repository for testing migration from gitlab to gitea", + CloneURL: "https://gitlab.com/gitea/test_repo.git", + OriginalURL: "https://gitlab.com/gitea/test_repo", + DefaultBranch: "master", }, repo) topics, err := downloader.GetTopics() From c37e75be336831f37f7d020eb95223d456117ce5 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 19:48:57 +0200 Subject: [PATCH 40/46] rm unused --- modules/migrations/base/repo.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/migrations/base/repo.go b/modules/migrations/base/repo.go index d2052da90d2b..d26a9118545d 100644 --- a/modules/migrations/base/repo.go +++ b/modules/migrations/base/repo.go @@ -12,8 +12,6 @@ type Repository struct { IsPrivate bool IsMirror bool Description string - AuthUsername string - AuthPassword string CloneURL string OriginalURL string DefaultBranch string From c3511c994f6f5d783611362e0ccff75b599bacb2 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 19:49:57 +0200 Subject: [PATCH 41/46] Update SDK to v0.13.0 --- go.mod | 2 +- go.sum | 4 +- vendor/code.gitea.io/sdk/gitea/client.go | 76 ++++++++++++++++--- .../sdk/gitea/issue_milestone.go | 73 +++++++++++++++++- vendor/modules.txt | 2 +- 5 files changed, 142 insertions(+), 15 deletions(-) diff --git a/go.mod b/go.mod index b8d7a1550717..257db25f3c4e 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.14 require ( code.gitea.io/gitea-vet v0.2.1 - code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd + code.gitea.io/sdk/gitea v0.13.0 gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 diff --git a/go.sum b/go.sum index 927424ca00f2..ca7f5176f657 100644 --- a/go.sum +++ b/go.sum @@ -15,8 +15,8 @@ cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2k cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd h1:ELLGt+i91Ffpj/RKEfzN7TwO51KH42JhP7ZbHamWAz4= -code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= +code.gitea.io/sdk/gitea v0.13.0 h1:iHognp8ZMhMFLooUUNZFpm8IHaC9qoHJDvAE5vTm5aw= +code.gitea.io/sdk/gitea v0.13.0/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go index 7cadebd9dd33..7516ff6d7ee2 100644 --- a/vendor/code.gitea.io/sdk/gitea/client.go +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -6,6 +6,7 @@ package gitea import ( + "context" "encoding/json" "errors" "fmt" @@ -34,6 +35,7 @@ type Client struct { otp string sudo string client *http.Client + ctx context.Context serverVersion *version.Version versionLock sync.RWMutex } @@ -44,43 +46,97 @@ type Response struct { } // NewClient initializes and returns a API client. -func NewClient(url, token string) *Client { - return &Client{ - url: strings.TrimSuffix(url, "/"), - accessToken: token, - client: &http.Client{}, +func NewClient(url string, options ...func(*Client)) (*Client, error) { + client := &Client{ + url: strings.TrimSuffix(url, "/"), + client: &http.Client{}, + ctx: context.Background(), } + for _, opt := range options { + opt(client) + } + if err := client.CheckServerVersionConstraint(">=1.10"); err != nil { + return nil, err + } + return client, nil } // NewClientWithHTTP creates an API client with a custom http client +// Deprecated use SetHTTPClient option func NewClientWithHTTP(url string, httpClient *http.Client) *Client { - client := NewClient(url, "") - client.client = httpClient + client, _ := NewClient(url, SetHTTPClient(httpClient)) return client } -// SetBasicAuth sets basicauth +// SetHTTPClient is an option for NewClient to set custom http client +func SetHTTPClient(httpClient *http.Client) func(client *Client) { + return func(client *Client) { + client.client = httpClient + } +} + +// SetToken is an option for NewClient to set token +func SetToken(token string) func(client *Client) { + return func(client *Client) { + client.accessToken = token + } +} + +// SetBasicAuth is an option for NewClient to set username and password +func SetBasicAuth(username, password string) func(client *Client) { + return func(client *Client) { + client.SetBasicAuth(username, password) + } +} + +// SetBasicAuth sets username and password func (c *Client) SetBasicAuth(username, password string) { c.username, c.password = username, password } +// SetOTP is an option for NewClient to set OTP for 2FA +func SetOTP(otp string) func(client *Client) { + return func(client *Client) { + client.SetOTP(otp) + } +} + // SetOTP sets OTP for 2FA func (c *Client) SetOTP(otp string) { c.otp = otp } +// SetContext is an option for NewClient to set context +func SetContext(ctx context.Context) func(client *Client) { + return func(client *Client) { + client.SetContext(ctx) + } +} + +// SetContext set context witch is used for http requests +func (c *Client) SetContext(ctx context.Context) { + c.ctx = ctx +} + // SetHTTPClient replaces default http.Client with user given one. func (c *Client) SetHTTPClient(client *http.Client) { c.client = client } +// SetSudo is an option for NewClient to set sudo header +func SetSudo(sudo string) func(client *Client) { + return func(client *Client) { + client.SetSudo(sudo) + } +} + // SetSudo sets username to impersonate. func (c *Client) SetSudo(sudo string) { c.sudo = sudo } func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) { - req, err := http.NewRequest(method, c.url+path, body) + req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body) if err != nil { return nil, nil, err } @@ -95,7 +151,7 @@ func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *R } func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) { - req, err := http.NewRequest(method, c.url+"/api/v1"+path, body) + req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body) if err != nil { return nil, err } diff --git a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go index 11719f22ec74..236c2367b57a 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -65,6 +65,18 @@ func (c *Client) GetMilestone(owner, repo string, id int64) (*Milestone, *Respon return milestone, resp, err } +// GetMilestoneByName get one milestone by repo and milestone name +func (c *Client) GetMilestoneByName(owner, repo string, name string) (*Milestone, *Response, error) { + if c.CheckServerVersionConstraint(">=1.13") != nil { + // backwards compatibility mode + m, resp, err := c.resolveMilestoneByName(owner, repo, name) + return m, resp, err + } + milestone := new(Milestone) + resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), nil, nil, milestone) + return milestone, resp, err +} + // CreateMilestoneOption options for creating a milestone type CreateMilestoneOption struct { Title string `json:"title"` @@ -135,8 +147,67 @@ func (c *Client) EditMilestone(owner, repo string, id int64, opt EditMilestoneOp return milestone, resp, err } -// DeleteMilestone delete one milestone by milestone id +// EditMilestoneByName modify milestone with options +func (c *Client) EditMilestoneByName(owner, repo string, name string, opt EditMilestoneOption) (*Milestone, *Response, error) { + if c.CheckServerVersionConstraint(">=1.13") != nil { + // backwards compatibility mode + m, _, err := c.resolveMilestoneByName(owner, repo, name) + if err != nil { + return nil, nil, err + } + return c.EditMilestone(owner, repo, m.ID, opt) + } + if err := opt.Validate(); err != nil { + return nil, nil, err + } + body, err := json.Marshal(&opt) + if err != nil { + return nil, nil, err + } + milestone := new(Milestone) + resp, err := c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), jsonHeader, bytes.NewReader(body), milestone) + return milestone, resp, err +} + +// DeleteMilestone delete one milestone by id func (c *Client) DeleteMilestone(owner, repo string, id int64) (*Response, error) { _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%d", owner, repo, id), nil, nil) return resp, err } + +// DeleteMilestoneByName delete one milestone by name +func (c *Client) DeleteMilestoneByName(owner, repo string, name string) (*Response, error) { + if c.CheckServerVersionConstraint(">=1.13") != nil { + // backwards compatibility mode + m, _, err := c.resolveMilestoneByName(owner, repo, name) + if err != nil { + return nil, err + } + return c.DeleteMilestone(owner, repo, m.ID) + } + _, resp, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/milestones/%s", owner, repo, name), nil, nil) + return resp, err +} + +// resolveMilestoneByName is a fallback method to find milestone id by name +func (c *Client) resolveMilestoneByName(owner, repo, name string) (*Milestone, *Response, error) { + for i := 1; ; i++ { + miles, resp, err := c.ListRepoMilestones(owner, repo, ListMilestoneOption{ + ListOptions: ListOptions{ + Page: i, + }, + State: "all", + }) + if err != nil { + return nil, nil, err + } + if len(miles) == 0 { + return nil, nil, fmt.Errorf("milestone '%s' do not exist", name) + } + for _, m := range miles { + if strings.ToLower(strings.TrimSpace(m.Title)) == strings.ToLower(strings.TrimSpace(name)) { + return m, resp, nil + } + } + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index dfd64a859a3e..e213b680ab21 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,7 +4,7 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks -# code.gitea.io/sdk/gitea v0.12.1-0.20200914023709-688ee1978edd +# code.gitea.io/sdk/gitea v0.13.0 ## explicit code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0 From 180ef4a5c757b41487fa5477f1211a4d8e4635d0 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 15 Sep 2020 19:55:42 +0200 Subject: [PATCH 42/46] addopt sdk changes --- modules/migrations/gitea_downloader.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/modules/migrations/gitea_downloader.go b/modules/migrations/gitea_downloader.go index f00d6cdbfac7..827cbef5c20d 100644 --- a/modules/migrations/gitea_downloader.go +++ b/modules/migrations/gitea_downloader.go @@ -80,14 +80,13 @@ type GiteaDownloader struct { // Use either a username/password or personal token. token is preferred // Note: Public access only allows very basic access func NewGiteaDownloader(ctx context.Context, baseURL, repoPath, username, password, token string) (*GiteaDownloader, error) { - giteaClient := gitea_sdk.NewClient(baseURL, token) - if token == "" { - giteaClient.SetBasicAuth(username, password) - } - - // do not support gitea instances older that 1.10 - // because gitea v1.10.0 first got the needed pull & release endpoints - if err := giteaClient.CheckServerVersionConstraint(">=1.10"); err != nil { + giteaClient, err := gitea_sdk.NewClient( + baseURL, + gitea_sdk.SetToken(token), + gitea_sdk.SetBasicAuth(username, password), + gitea_sdk.SetContext(ctx), + ) + if err != nil { log.Error(fmt.Sprintf("NewGiteaDownloader: %s", err.Error())) return nil, err } From 8679be8088148a80a81b1f175f8db7d53d5a11eb Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Fri, 18 Sep 2020 15:58:39 +0200 Subject: [PATCH 43/46] found better link --- templates/repo/migrate/gitea.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 23d231fe9989..4e2a70cf211b 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -22,7 +22,7 @@
- {{svg "octicon-question"}} + {{svg "octicon-question"}}
From dcd9726461acb41b6d83e9c93ef95a8b4a2c285b Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 21 Sep 2020 00:55:23 +0200 Subject: [PATCH 44/46] format template --- templates/repo/migrate/gitea.tmpl | 34 +++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 4e2a70cf211b..2996d3f67670 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -6,7 +6,7 @@ {{.CsrfTokenHtml}}

{{.i18n.Tr "repo.migrate.migrate" .service.Title}} - +

{{template "base/alert" .}} @@ -14,15 +14,15 @@ - {{.i18n.Tr "repo.migrate.clone_address_desc"}}{{if .ContextUser.CanImportLocal}} {{.i18n.Tr "repo.migrate.clone_local_path"}}{{end}} - {{if .LFSActive}}
{{.i18n.Tr "repo.migrate.lfs_mirror_unsupported"}}{{end}} + {{.i18n.Tr "repo.migrate.clone_address_desc"}}{{if .ContextUser.CanImportLocal}} {{.i18n.Tr "repo.migrate.clone_local_path"}}{{end}} + {{if .LFSActive}}
{{.i18n.Tr "repo.migrate.lfs_mirror_unsupported"}}{{end}}
- - {{svg "octicon-question"}} + + {{svg "octicon-question"}}
@@ -32,7 +32,7 @@ {{else}} - + {{end}}
@@ -43,33 +43,33 @@
- +
- +
- +
- +
- +
- +
@@ -92,10 +92,10 @@ {{.SignedUser.ShortName 20}}
{{range .Orgs}} -
- - {{.ShortName 20}} -
+
+ + {{.ShortName 20}} +
{{end}} @@ -112,7 +112,7 @@ {{else}} - + {{end}} From 3e1aa5499649a0f0af19325b635de4221a18f7c9 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 21 Sep 2020 18:09:15 +0200 Subject: [PATCH 45/46] Update Docs --- docs/content/doc/advanced/migrations.en-us.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/content/doc/advanced/migrations.en-us.md b/docs/content/doc/advanced/migrations.en-us.md index 2097dbbf66a8..746c68f42672 100644 --- a/docs/content/doc/advanced/migrations.en-us.md +++ b/docs/content/doc/advanced/migrations.en-us.md @@ -17,10 +17,10 @@ menu: The new migration features were introduced in Gitea 1.9.0. It defines two interfaces to support migrating repositories data from other git host platforms to gitea or, in the future migrating gitea data to other -git host platforms. Currently, only the migrations from github via APIv3 to Gitea is implemented. +git host platforms. Currently, migrations from Github, Gitlab and Gitea to Gitea is implemented. First of all, Gitea defines some standard objects in packages `modules/migrations/base`. They are - `Repository`, `Milestone`, `Release`, `Label`, `Issue`, `Comment`, `PullRequest`, `Reaction`, `Review`, `ReviewComment`. + `Repository`, `Milestone`, `Release`, `ReleaseAsset`, `Label`, `Issue`, `Comment`, `PullRequest`, `Reaction`, `Review`, `ReviewComment`. ## Downloader Interfaces @@ -33,6 +33,7 @@ create a Downloader. ```Go type Downloader interface { + GetAsset(relTag string, relID, id int64) (io.ReadCloser, error) SetContext(context.Context) GetRepoInfo() (*Repository, error) GetTopics() ([]string, error) @@ -41,15 +42,15 @@ type Downloader interface { GetLabels() ([]*Label, error) GetIssues(page, perPage int) ([]*Issue, bool, error) GetComments(issueNumber int64) ([]*Comment, error) - GetPullRequests(page, perPage int) ([]*PullRequest, error) + GetPullRequests(page, perPage int) ([]*PullRequest, bool, error) GetReviews(pullRequestNumber int64) ([]*Review, error) } ``` ```Go type DownloaderFactory interface { - Match(opts MigrateOptions) (bool, error) - New(opts MigrateOptions) (Downloader, error) + New(ctx context.Context, opts MigrateOptions) (Downloader, error) + GitServiceType() structs.GitServiceType } ``` @@ -66,7 +67,7 @@ type Uploader interface { CreateRepo(repo *Repository, opts MigrateOptions) error CreateTopics(topic ...string) error CreateMilestones(milestones ...*Milestone) error - CreateReleases(releases ...*Release) error + CreateReleases(downloader Downloader, releases ...*Release) error SyncTags() error CreateLabels(labels ...*Label) error CreateIssues(issues ...*Issue) error From 228c20a94f839e83910c3bf4bb26eaa1bdc5c4cf Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Tue, 29 Sep 2020 19:59:59 +0200 Subject: [PATCH 46/46] Update Gitea SDK (v0.13.1) --- go.mod | 2 +- go.sum | 4 +-- vendor/code.gitea.io/sdk/gitea/client.go | 22 +++++++++++- .../code.gitea.io/sdk/gitea/notifications.go | 9 ++--- vendor/code.gitea.io/sdk/gitea/release.go | 35 ++++++++++++++++++- vendor/modules.txt | 2 +- 6 files changed, 64 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 7d450b1d9f12..7d7aee6dfce6 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.14 require ( code.gitea.io/gitea-vet v0.2.1 - code.gitea.io/sdk/gitea v0.13.0 + code.gitea.io/sdk/gitea v0.13.1 gitea.com/lunny/levelqueue v0.3.0 gitea.com/macaron/binding v0.0.0-20190822013154-a5f53841ed2b gitea.com/macaron/cache v0.0.0-20190822004001-a6e7fee4ee76 diff --git a/go.sum b/go.sum index c23b7bbcedef..a02953302f97 100644 --- a/go.sum +++ b/go.sum @@ -15,8 +15,8 @@ cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2k cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= code.gitea.io/gitea-vet v0.2.1 h1:b30by7+3SkmiftK0RjuXqFvZg2q4p68uoPGuxhzBN0s= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/sdk/gitea v0.13.0 h1:iHognp8ZMhMFLooUUNZFpm8IHaC9qoHJDvAE5vTm5aw= -code.gitea.io/sdk/gitea v0.13.0/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= +code.gitea.io/sdk/gitea v0.13.1 h1:Y7bpH2iO6Q0KhhMJfjP/LZ0AmiYITeRQlCD8b0oYqhk= +code.gitea.io/sdk/gitea v0.13.1/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= gitea.com/lunny/levelqueue v0.3.0 h1:MHn1GuSZkxvVEDMyAPqlc7A3cOW+q8RcGhRgH/xtm6I= gitea.com/lunny/levelqueue v0.3.0/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU= diff --git a/vendor/code.gitea.io/sdk/gitea/client.go b/vendor/code.gitea.io/sdk/gitea/client.go index 7516ff6d7ee2..ca5ee35334a7 100644 --- a/vendor/code.gitea.io/sdk/gitea/client.go +++ b/vendor/code.gitea.io/sdk/gitea/client.go @@ -34,6 +34,7 @@ type Client struct { password string otp string sudo string + debug bool client *http.Client ctx context.Context serverVersion *version.Version @@ -135,7 +136,17 @@ func (c *Client) SetSudo(sudo string) { c.sudo = sudo } +// SetDebugMode is an option for NewClient to enable debug mode +func SetDebugMode() func(client *Client) { + return func(client *Client) { + client.debug = true + } +} + func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *Response, error) { + if c.debug { + fmt.Printf("%s: %s\nBody: %v\n", method, c.url+path, body) + } req, err := http.NewRequestWithContext(c.ctx, method, c.url+path, body) if err != nil { return nil, nil, err @@ -147,10 +158,16 @@ func (c *Client) getWebResponse(method, path string, body io.Reader) ([]byte, *R defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) + if c.debug { + fmt.Printf("Response: %v\n\n", resp) + } return data, &Response{resp}, nil } func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*Response, error) { + if c.debug { + fmt.Printf("%s: %s\nHeader: %v\nBody: %s\n", method, c.url+"/api/v1"+path, header, body) + } req, err := http.NewRequestWithContext(c.ctx, method, c.url+"/api/v1"+path, body) if err != nil { return nil, err @@ -175,6 +192,9 @@ func (c *Client) doRequest(method, path string, header http.Header, body io.Read if err != nil { return nil, err } + if c.debug { + fmt.Printf("Response: %v\n\n", resp) + } return &Response{resp}, nil } @@ -217,7 +237,7 @@ func (c *Client) getResponse(method, path string, header http.Header, body io.Re func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) (*Response, error) { data, resp, err := c.getResponse(method, path, header, body) if err != nil { - return nil, err + return resp, err } return resp, json.Unmarshal(data, obj) } diff --git a/vendor/code.gitea.io/sdk/gitea/notifications.go b/vendor/code.gitea.io/sdk/gitea/notifications.go index 8f69cb3aae8a..515a0d4a7128 100644 --- a/vendor/code.gitea.io/sdk/gitea/notifications.go +++ b/vendor/code.gitea.io/sdk/gitea/notifications.go @@ -23,10 +23,11 @@ type NotificationThread struct { // 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)"` + Title string `json:"title"` + URL string `json:"url"` + LatestCommentURL string `json:"latest_comment_url"` + Type string `json:"type"` + State StateType `json:"state"` } // NotifyStatus notification status type diff --git a/vendor/code.gitea.io/sdk/gitea/release.go b/vendor/code.gitea.io/sdk/gitea/release.go index 3ce204a1a10d..3440f1c61bb6 100644 --- a/vendor/code.gitea.io/sdk/gitea/release.go +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/json" "fmt" + "net/http" "strings" "time" ) @@ -45,11 +46,23 @@ func (c *Client) ListReleases(user, repo string, opt ListReleasesOptions) ([]*Re return releases, resp, err } -// GetRelease get a release of a repository +// GetRelease get a release of a repository by id func (c *Client) GetRelease(user, repo string, id int64) (*Release, *Response, error) { r := new(Release) resp, err := c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/releases/%d", user, repo, id), + jsonHeader, nil, &r) + return r, resp, err +} + +// GetReleaseByTag get a release of a repository by tag +func (c *Client) GetReleaseByTag(user, repo string, tag string) (*Release, *Response, error) { + if c.CheckServerVersionConstraint(">=1.13.0") != nil { + return c.fallbackGetReleaseByTag(user, repo, tag) + } + r := new(Release) + resp, err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/tags/%s", user, repo, tag), nil, nil, &r) return r, resp, err } @@ -118,3 +131,23 @@ func (c *Client) DeleteRelease(user, repo string, id int64) (*Response, error) { nil, nil) return resp, err } + +// fallbackGetReleaseByTag is fallback for old gitea installations ( < 1.13.0 ) +func (c *Client) fallbackGetReleaseByTag(user, repo string, tag string) (*Release, *Response, error) { + for i := 1; ; i++ { + rl, resp, err := c.ListReleases(user, repo, ListReleasesOptions{ListOptions{Page: i}}) + if err != nil { + return nil, resp, err + } + if len(rl) == 0 { + return nil, + &Response{&http.Response{StatusCode: 404}}, + fmt.Errorf("release with tag '%s' not found", tag) + } + for _, r := range rl { + if r.TagName == tag { + return r, resp, nil + } + } + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 12ab59f68bbd..f4061ccc9684 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,7 +4,7 @@ cloud.google.com/go/compute/metadata ## explicit code.gitea.io/gitea-vet code.gitea.io/gitea-vet/checks -# code.gitea.io/sdk/gitea v0.13.0 +# code.gitea.io/sdk/gitea v0.13.1 ## explicit code.gitea.io/sdk/gitea # gitea.com/lunny/levelqueue v0.3.0