From 818f4715b15ace4ff112fd2e30063f5139549f6a Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 01:02:58 +0800 Subject: [PATCH 01/21] Priority updating api for issues (both web and api). Signed-off-by: BetaCat0 outman99@hotmail.com --- models/error.go | 27 +- models/fixtures/issue.yml | 6 + models/issue.go | 30 +- models/issus_priority.go | 45 ++ models/issus_priority_test.go | 39 ++ models/transaction.go | 30 + modules/auth/repo_form.go | 6 + routers/api/v1/api.go | 4 +- routers/api/v1/repo/issue.go | 72 +++ routers/repo/issue.go | 18 + routers/repo/issue_test.go | 36 ++ routers/routes/routes.go | 3 +- vendor/code.gitea.io/git/LICENSE | 20 - vendor/code.gitea.io/git/blob.go | 73 --- vendor/code.gitea.io/git/command.go | 134 ----- vendor/code.gitea.io/git/commit.go | 276 --------- vendor/code.gitea.io/git/commit_archive.go | 37 -- vendor/code.gitea.io/git/commit_info.go | 319 ----------- vendor/code.gitea.io/git/doc.go | 5 - vendor/code.gitea.io/git/error.go | 66 --- vendor/code.gitea.io/git/git.go | 91 --- vendor/code.gitea.io/git/hook.go | 126 ----- vendor/code.gitea.io/git/parse.go | 81 --- vendor/code.gitea.io/git/repo.go | 287 ---------- vendor/code.gitea.io/git/repo_blame.go | 24 - vendor/code.gitea.io/git/repo_branch.go | 123 ---- vendor/code.gitea.io/git/repo_commit.go | 352 ------------ vendor/code.gitea.io/git/repo_hook.go | 15 - vendor/code.gitea.io/git/repo_object.go | 19 - vendor/code.gitea.io/git/repo_pull.go | 89 --- vendor/code.gitea.io/git/repo_tag.go | 157 ------ vendor/code.gitea.io/git/repo_tree.go | 26 - vendor/code.gitea.io/git/sha1.go | 76 --- vendor/code.gitea.io/git/signature.go | 58 -- vendor/code.gitea.io/git/submodule.go | 79 --- vendor/code.gitea.io/git/tag.go | 89 --- vendor/code.gitea.io/git/tree.go | 72 --- vendor/code.gitea.io/git/tree_blob.go | 59 -- vendor/code.gitea.io/git/tree_entry.go | 200 ------- vendor/code.gitea.io/git/utils.go | 96 ---- vendor/code.gitea.io/sdk/LICENSE | 20 - vendor/code.gitea.io/sdk/gitea/admin_org.go | 22 - vendor/code.gitea.io/sdk/gitea/admin_repo.go | 22 - vendor/code.gitea.io/sdk/gitea/admin_user.go | 82 --- vendor/code.gitea.io/sdk/gitea/attachment.go | 92 --- vendor/code.gitea.io/sdk/gitea/doc.go | 5 - vendor/code.gitea.io/sdk/gitea/fork.go | 39 -- vendor/code.gitea.io/sdk/gitea/gitea.go | 104 ---- vendor/code.gitea.io/sdk/gitea/hook.go | 531 ------------------ vendor/code.gitea.io/sdk/gitea/issue.go | 154 ----- .../code.gitea.io/sdk/gitea/issue_comment.go | 76 --- vendor/code.gitea.io/sdk/gitea/issue_label.go | 122 ---- .../sdk/gitea/issue_milestone.go | 80 --- .../sdk/gitea/issue_tracked_time.go | 68 --- vendor/code.gitea.io/sdk/gitea/lfs_lock.go | 65 --- .../code.gitea.io/sdk/gitea/miscellaneous.go | 52 -- vendor/code.gitea.io/sdk/gitea/org.go | 68 --- vendor/code.gitea.io/sdk/gitea/org_member.go | 26 - vendor/code.gitea.io/sdk/gitea/org_team.go | 32 -- vendor/code.gitea.io/sdk/gitea/pull.go | 151 ----- vendor/code.gitea.io/sdk/gitea/release.go | 105 ---- vendor/code.gitea.io/sdk/gitea/repo.go | 155 ----- vendor/code.gitea.io/sdk/gitea/repo_branch.go | 27 - .../sdk/gitea/repo_collaborator.go | 57 -- vendor/code.gitea.io/sdk/gitea/repo_file.go | 15 - vendor/code.gitea.io/sdk/gitea/repo_key.go | 69 --- vendor/code.gitea.io/sdk/gitea/repo_watch.go | 41 -- vendor/code.gitea.io/sdk/gitea/status.go | 97 ---- vendor/code.gitea.io/sdk/gitea/user.go | 51 -- vendor/code.gitea.io/sdk/gitea/user_app.go | 63 --- vendor/code.gitea.io/sdk/gitea/user_email.go | 56 -- vendor/code.gitea.io/sdk/gitea/user_follow.go | 55 -- vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 80 --- vendor/code.gitea.io/sdk/gitea/user_key.go | 57 -- vendor/code.gitea.io/sdk/gitea/user_search.go | 14 - vendor/code.gitea.io/sdk/gitea/utils.go | 26 - 76 files changed, 296 insertions(+), 5848 deletions(-) create mode 100644 models/issus_priority.go create mode 100644 models/issus_priority_test.go create mode 100644 models/transaction.go create mode 100644 routers/repo/issue_test.go delete mode 100644 vendor/code.gitea.io/git/LICENSE delete mode 100644 vendor/code.gitea.io/git/blob.go delete mode 100644 vendor/code.gitea.io/git/command.go delete mode 100644 vendor/code.gitea.io/git/commit.go delete mode 100644 vendor/code.gitea.io/git/commit_archive.go delete mode 100644 vendor/code.gitea.io/git/commit_info.go delete mode 100644 vendor/code.gitea.io/git/doc.go delete mode 100644 vendor/code.gitea.io/git/error.go delete mode 100644 vendor/code.gitea.io/git/git.go delete mode 100644 vendor/code.gitea.io/git/hook.go delete mode 100644 vendor/code.gitea.io/git/parse.go delete mode 100644 vendor/code.gitea.io/git/repo.go delete mode 100644 vendor/code.gitea.io/git/repo_blame.go delete mode 100644 vendor/code.gitea.io/git/repo_branch.go delete mode 100644 vendor/code.gitea.io/git/repo_commit.go delete mode 100644 vendor/code.gitea.io/git/repo_hook.go delete mode 100644 vendor/code.gitea.io/git/repo_object.go delete mode 100644 vendor/code.gitea.io/git/repo_pull.go delete mode 100644 vendor/code.gitea.io/git/repo_tag.go delete mode 100644 vendor/code.gitea.io/git/repo_tree.go delete mode 100644 vendor/code.gitea.io/git/sha1.go delete mode 100644 vendor/code.gitea.io/git/signature.go delete mode 100644 vendor/code.gitea.io/git/submodule.go delete mode 100644 vendor/code.gitea.io/git/tag.go delete mode 100644 vendor/code.gitea.io/git/tree.go delete mode 100644 vendor/code.gitea.io/git/tree_blob.go delete mode 100644 vendor/code.gitea.io/git/tree_entry.go delete mode 100644 vendor/code.gitea.io/git/utils.go delete mode 100644 vendor/code.gitea.io/sdk/LICENSE delete mode 100644 vendor/code.gitea.io/sdk/gitea/admin_org.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/admin_repo.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/admin_user.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/attachment.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/doc.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/fork.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/gitea.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/hook.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_comment.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_label.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_milestone.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/lfs_lock.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/miscellaneous.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org_member.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org_team.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/pull.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/release.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_branch.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_collaborator.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_file.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_key.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_watch.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/status.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_app.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_email.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_follow.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_gpgkey.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_key.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_search.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/utils.go diff --git a/models/error.go b/models/error.go index b079f06d842a8..492f80214cb69 100644 --- a/models/error.go +++ b/models/error.go @@ -521,11 +521,11 @@ func (err ErrLastOrgOwner) Error() string { return fmt.Sprintf("user is the last member of owner team [uid: %d]", err.UID) } -//.____ ____________________ -//| | \_ _____/ _____/ -//| | | __) \_____ \ -//| |___| \ / \ -//|_______ \___ / /_______ / +// .____ ____________________ +// | | \_ _____/ _____/ +// | | | __) \_____ \ +// | |___| \ / \ +// |_______ \___ / /_______ / // \/ \/ \/ // ErrLFSLockNotExist represents a "LFSLockNotExist" kind of error. @@ -877,6 +877,23 @@ func (err ErrIssueNotExist) Error() string { return fmt.Sprintf("issue does not exist [id: %d, repo_id: %d, index: %d]", err.ID, err.RepoID, err.Index) } +// ErrIssueInvalidPriority represents a "IssueInvalidPriority" kind of error. +type ErrIssueInvalidPriority struct { + ID int64 + RepoID int64 + DesiredPriority int +} + +// ErrIssueInvalidPriority checks if an error is a ErrIssueInvalidPriority. +func IsErrIssueInvalidPriority(err error) bool { + _, ok := err.(ErrIssueInvalidPriority) + return ok +} + +func (err ErrIssueInvalidPriority) Error() string { + return fmt.Sprintf("issue exceeds the threshold priority [id: %d, repo_id: %d, desired_priority: %d]", err.ID, err.RepoID, err.DesiredPriority) +} + // __________ .__ .__ __________ __ // \______ \__ __| | | |\______ \ ____ ________ __ ____ _______/ |_ // | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\ diff --git a/models/fixtures/issue.yml b/models/fixtures/issue.yml index 4de8c4fa7e2cf..45ccf2b486d20 100644 --- a/models/fixtures/issue.yml +++ b/models/fixtures/issue.yml @@ -4,6 +4,7 @@ index: 1 poster_id: 1 name: issue1 + priority: 1 content: content for the first issue is_closed: false is_pull: false @@ -17,6 +18,7 @@ index: 2 poster_id: 1 name: issue2 + priority: 2 content: content for the second issue milestone_id: 1 is_closed: false @@ -31,6 +33,7 @@ index: 3 poster_id: 1 name: issue3 + priority: 3 content: content for the third issue is_closed: false is_pull: true @@ -43,6 +46,7 @@ index: 1 poster_id: 2 name: issue4 + priority: 4 content: content for the fourth issue is_closed: true is_pull: false @@ -55,6 +59,7 @@ index: 4 poster_id: 2 name: issue5 + priority: 5 content: content for the fifth issue is_closed: true is_pull: false @@ -67,6 +72,7 @@ index: 1 poster_id: 1 name: issue6 + priority: 5 content: content6 is_closed: false is_pull: false diff --git a/models/issue.go b/models/issue.go index a3274104358df..0039498e7b81a 100644 --- a/models/issue.go +++ b/models/issue.go @@ -24,19 +24,19 @@ import ( // Issue represents an issue or pull request of repository. type Issue struct { - ID int64 `xorm:"pk autoincr"` - RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"` - Repo *Repository `xorm:"-"` - Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository. - PosterID int64 `xorm:"INDEX"` - Poster *User `xorm:"-"` - Title string `xorm:"name"` - Content string `xorm:"TEXT"` - RenderedContent string `xorm:"-"` - Labels []*Label `xorm:"-"` - MilestoneID int64 `xorm:"INDEX"` - Milestone *Milestone `xorm:"-"` - Priority int + ID int64 `xorm:"pk autoincr"` + RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"` + Repo *Repository `xorm:"-"` + Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository. + PosterID int64 `xorm:"INDEX"` + Poster *User `xorm:"-"` + Title string `xorm:"name"` + Content string `xorm:"TEXT"` + RenderedContent string `xorm:"-"` + Labels []*Label `xorm:"-"` + MilestoneID int64 `xorm:"INDEX"` + Milestone *Milestone `xorm:"-"` + Priority int `xorm:"priority"` // Indicates priority in list display AssigneeID int64 `xorm:"-"` Assignee *User `xorm:"-"` IsClosed bool `xorm:"INDEX"` @@ -1271,6 +1271,10 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) { if err := opts.setupSession(sess); err != nil { return nil, err } + // issues with high-level priorities are first in the result set. + if opts.SortType != "priority" { + sortIssuesSession(sess, "priority") + } sortIssuesSession(sess, opts.SortType) issues := make([]*Issue, 0, setting.UI.IssuePagingNum) diff --git a/models/issus_priority.go b/models/issus_priority.go new file mode 100644 index 0000000000000..07facb9d2bd71 --- /dev/null +++ b/models/issus_priority.go @@ -0,0 +1,45 @@ +// 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 models + +import ( + "github.com/go-xorm/xorm" +) + +const ( + // LowestPriority defines the lowest-level priority + LowestPriority = iota + 1 + // LowPriority defines the low-level priority + LowPriority + // MediumPriority defines the medium-level priority + MediumPriority + // HighPriority defines the high-level priority + HighPriority + // HighestPriority defines the highest-level priority + HighestPriority +) + +// UpdateIssuePriority update priority for a specific issue +func UpdateIssuePriority(issue *Issue, doer *User) error { + if err := issue.loadRepo(x); err != nil { + return err + } + + if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil { + return err + } else if !has { + return ErrUserDoesNotHaveAccessToRepo{UserID: doer.ID, RepoName: issue.Repo.Name} + } + + if issue.Priority > HighestPriority || issue.Priority < LowestPriority { + return ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority} + } + + _, err := AutoTransaction(func(session *xorm.Session) (interface{}, error) { + return nil, updateIssueCols(session, &Issue{ID: issue.ID, Priority: issue.Priority}, "priority") + }, x) + + return err +} diff --git a/models/issus_priority_test.go b/models/issus_priority_test.go new file mode 100644 index 0000000000000..86fa6b818afd3 --- /dev/null +++ b/models/issus_priority_test.go @@ -0,0 +1,39 @@ +// 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 models + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestUpdateIssuePriority(t *testing.T) { + assert.NoError(t, PrepareTestDatabase()) + + issue := AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + repo := AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) + doer := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + + issue.Priority = HighestPriority + + err := UpdateIssuePriority(issue, doer) + assert.NoError(t, err) + + issue = AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.EqualValues(t, HighestPriority, issue.Priority) + + issue.Priority = -1 + err = UpdateIssuePriority(issue, doer) + assert.Error(t, err) + assert.EqualValues( + t, err, ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) + + issue.Priority = 6 + err = UpdateIssuePriority(issue, doer) + assert.Error(t, err) + assert.EqualValues( + t, err, ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) +} diff --git a/models/transaction.go b/models/transaction.go new file mode 100644 index 0000000000000..fdd2e1365a6a0 --- /dev/null +++ b/models/transaction.go @@ -0,0 +1,30 @@ +// 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 models + +import ( + "github.com/go-xorm/xorm" +) + +// AutoTransaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred +func AutoTransaction(f func(*xorm.Session) (interface{}, error), engine *xorm.Engine) (interface{}, error) { + session := engine.NewSession() + defer session.Close() + + if err := session.Begin(); err != nil { + return nil, err + } + + result, err := f(session) + if err != nil { + return nil, err + } + + if err := session.Commit(); err != nil { + return nil, err + } + + return result, nil +} diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index 3c7940afce756..7ba3eae7dda94 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -280,6 +280,12 @@ type CreateCommentForm struct { Files []string } +// EditPriorityForm form for updating priority +type EditPriorityForm struct { + // required:true + Priority int `binding:"Required;Range(1,5)"` +} + // Validate validates the fields func (f *CreateCommentForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors { return validate(errs, ctx.Data, f, ctx.Locale) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 47a8edab438fa..a1a03de922bbf 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -287,7 +287,7 @@ func RegisterRoutes(m *macaron.Macaron) { bind := binding.Bind if setting.API.EnableSwagger { - m.Get("/swagger", misc.Swagger) //Render V1 by default + m.Get("/swagger", misc.Swagger) // Render V1 by default } m.Group("/v1", func() { @@ -457,6 +457,8 @@ func RegisterRoutes(m *macaron.Macaron) { }) m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) + + m.Combo("/priority").Patch(reqToken(), bind(api.EditPriorityOption{}), repo.UpdateIssuePriority) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index f8ef0fe3d9c05..827228bff7ad4 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -178,6 +178,7 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { Poster: ctx.User, Content: form.Body, DeadlineUnix: deadlineUnix, + Priority: models.LowestPriority, } var assigneeIDs = make([]int64, 0) @@ -416,3 +417,74 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { ctx.JSON(201, api.IssueDeadline{Deadline: form.Deadline}) } + +// UpdateIssuePriority updates an issue priority. +func UpdateIssuePriority(ctx *context.APIContext, form api.EditPriorityOption) { + // swagger:operation PATCH /repos/{owner}/{repo}/issues/{index}/priority issue issueUpdateIssuePriority + // --- + // summary: Update the priority of an issue. + // consumes: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue to update priority on + // type: integer + // required: true + // - name: body + // in: body + // schema: + // "$ref": "#/definitions/EditPriorityOption" + // responses: + // "200": + // "$ref": "#/responses/Issue" + // "403": + // description: Not repo writer + // schema: + // "$ref": "#/responses/forbidden" + // "404": + // description: Issue not found + // schema: + // "$ref": "#/responses/empty" + + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + if err != nil { + if models.IsErrIssueNotExist(err) { + ctx.Status(http.StatusNotFound) + } else { + ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) + } + + return + } + + if !ctx.Repo.IsWriter() { + ctx.Status(http.StatusForbidden) + return + } + + if form.Priority < models.LowestPriority || form.Priority > models.HighestPriority { + ctx.Error(http.StatusInternalServerError, + "UpdateIssuePriority", fmt.Sprintf("Invalid priority [%v]", form.Priority)) + + return + } + + if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) + + return + } + + ctx.JSON(http.StatusOK, issue.APIFormat()) +} diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 3cce483062fd2..b4b860d73728a 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -1541,3 +1541,21 @@ func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) { "html": html, }) } + +// UpdateIssuePriority updates an issue priority. +func UpdateIssuePriority(ctx *context.Context, form auth.EditPriorityForm) { + issue := GetActionIssue(ctx) + if ctx.Written() { + return + } + + issue.Priority = form.Priority + + if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + ctx.Error(http.StatusInternalServerError) + + return + } + + ctx.JSON(http.StatusOK, tplIssues) +} diff --git a/routers/repo/issue_test.go b/routers/repo/issue_test.go new file mode 100644 index 0000000000000..a5360edf2691e --- /dev/null +++ b/routers/repo/issue_test.go @@ -0,0 +1,36 @@ +// 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 repo + +import ( + "net/http" + "testing" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth" + "code.gitea.io/gitea/modules/test" + "github.com/stretchr/testify/assert" +) + +func TestUpdateIssuePriority(t *testing.T) { + models.PrepareTestEnv(t) + + ctx := test.MockContext(t, "user2/repo1/issues/1/priority") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + test.LoadGitRepo(t, ctx) + UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: 2}) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + models.AssertExistsAndLoadBean(t, &models.Issue{ + ID: 1, + }, models.Cond("priority = ?", 2)) + + ctx = test.MockContext(t, "user2/repo1/issues/1/priority") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + test.LoadGitRepo(t, ctx) + UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: -1}) + assert.EqualValues(t, http.StatusInternalServerError, ctx.Resp.Status()) +} diff --git a/routers/routes/routes.go b/routers/routes/routes.go index e5476fd22706f..800df0cceed06 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -517,7 +517,7 @@ func RegisterRoutes(m *macaron.Macaron) { m.Combo("/new").Get(context.RepoRef(), repo.NewIssue). Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost) }, context.CheckUnit(models.UnitTypeIssues)) - // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest. + // FIXME: should use different URLs but mostly same logic for comments of issue and pull request. // So they can apply their own enable/disable logic on routers. m.Group("/issues", func() { m.Group("/:index", func() { @@ -537,6 +537,7 @@ func RegisterRoutes(m *macaron.Macaron) { }) }) m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction) + m.Patch("/priority", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.UpdateIssuePriority) }) m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel) diff --git a/vendor/code.gitea.io/git/LICENSE b/vendor/code.gitea.io/git/LICENSE deleted file mode 100644 index 10aeba46bcfc9..0000000000000 --- a/vendor/code.gitea.io/git/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -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/git/blob.go b/vendor/code.gitea.io/git/blob.go deleted file mode 100644 index a6e392eeb50a6..0000000000000 --- a/vendor/code.gitea.io/git/blob.go +++ /dev/null @@ -1,73 +0,0 @@ -// 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 git - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" -) - -// Blob represents a Git object. -type Blob struct { - repo *Repository - *TreeEntry -} - -// Data gets content of blob all at once and wrap it as io.Reader. -// This can be very slow and memory consuming for huge content. -func (b *Blob) Data() (io.Reader, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - - // Preallocate memory to save ~50% memory usage on big files. - stdout.Grow(int(b.Size() + 2048)) - - if err := b.DataPipeline(stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - return stdout, nil -} - -// DataPipeline gets content of blob and write the result or error to stdout or stderr -func (b *Blob) DataPipeline(stdout, stderr io.Writer) error { - return NewCommand("show", b.ID.String()).RunInDirPipeline(b.repo.Path, stdout, stderr) -} - -type cmdReadCloser struct { - cmd *exec.Cmd - stdout io.Reader -} - -func (c cmdReadCloser) Read(p []byte) (int, error) { - return c.stdout.Read(p) -} - -func (c cmdReadCloser) Close() error { - io.Copy(ioutil.Discard, c.stdout) - return c.cmd.Wait() -} - -// DataAsync gets a ReadCloser for the contents of a blob without reading it all. -// Calling the Close function on the result will discard all unread output. -func (b *Blob) DataAsync() (io.ReadCloser, error) { - cmd := exec.Command("git", "show", b.ID.String()) - cmd.Dir = b.repo.Path - cmd.Stderr = os.Stderr - - stdout, err := cmd.StdoutPipe() - if err != nil { - return nil, fmt.Errorf("StdoutPipe: %v", err) - } - - if err = cmd.Start(); err != nil { - return nil, fmt.Errorf("Start: %v", err) - } - - return cmdReadCloser{stdout: stdout, cmd: cmd}, nil -} diff --git a/vendor/code.gitea.io/git/command.go b/vendor/code.gitea.io/git/command.go deleted file mode 100644 index 8ca99fd6d3add..0000000000000 --- a/vendor/code.gitea.io/git/command.go +++ /dev/null @@ -1,134 +0,0 @@ -// 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 git - -import ( - "bytes" - "context" - "fmt" - "io" - "os/exec" - "strings" - "time" -) - -var ( - // GlobalCommandArgs global command args for external package setting - GlobalCommandArgs []string - - // DefaultCommandExecutionTimeout default command execution timeout duration - DefaultCommandExecutionTimeout = 60 * time.Second -) - -// Command represents a command with its subcommands or arguments. -type Command struct { - name string - args []string -} - -func (c *Command) String() string { - if len(c.args) == 0 { - return c.name - } - return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " ")) -} - -// NewCommand creates and returns a new Git Command based on given command and arguments. -func NewCommand(args ...string) *Command { - return &Command{ - name: "git", - args: append(GlobalCommandArgs, args...), - } -} - -// AddArguments adds new argument(s) to the command. -func (c *Command) AddArguments(args ...string) *Command { - c.args = append(c.args, args...) - return c -} - -// RunInDirTimeoutPipeline executes the command in given directory with given timeout, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error { - if timeout == -1 { - timeout = DefaultCommandExecutionTimeout - } - - if len(dir) == 0 { - log(c.String()) - } else { - log("%s: %v", dir, c) - } - - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - - cmd := exec.CommandContext(ctx, c.name, c.args...) - cmd.Dir = dir - cmd.Stdout = stdout - cmd.Stderr = stderr - if err := cmd.Start(); err != nil { - return err - } - - if err := cmd.Wait(); err != nil { - return err - } - - return ctx.Err() -} - -// RunInDirTimeout executes the command in given directory with given timeout, -// and returns stdout in []byte and error (combined with stderr). -func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - if err := c.RunInDirTimeoutPipeline(timeout, dir, stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - - if stdout.Len() > 0 { - log("stdout:\n%s", stdout.Bytes()[:1024]) - } - return stdout.Bytes(), nil -} - -// RunInDirPipeline executes the command in given directory, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { - return c.RunInDirTimeoutPipeline(-1, dir, stdout, stderr) -} - -// RunInDirBytes executes the command in given directory -// and returns stdout in []byte and error (combined with stderr). -func (c *Command) RunInDirBytes(dir string) ([]byte, error) { - return c.RunInDirTimeout(-1, dir) -} - -// RunInDir executes the command in given directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunInDir(dir string) (string, error) { - stdout, err := c.RunInDirTimeout(-1, dir) - if err != nil { - return "", err - } - return string(stdout), nil -} - -// RunTimeout executes the command in defualt working directory with given timeout, -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunTimeout(timeout time.Duration) (string, error) { - stdout, err := c.RunInDirTimeout(timeout, "") - if err != nil { - return "", err - } - return string(stdout), nil -} - -// Run executes the command in defualt working directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) Run() (string, error) { - return c.RunTimeout(-1) -} diff --git a/vendor/code.gitea.io/git/commit.go b/vendor/code.gitea.io/git/commit.go deleted file mode 100644 index 299a2381b65b6..0000000000000 --- a/vendor/code.gitea.io/git/commit.go +++ /dev/null @@ -1,276 +0,0 @@ -// 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 git - -import ( - "bufio" - "bytes" - "container/list" - "fmt" - "net/http" - "strconv" - "strings" -) - -// Commit represents a git commit. -type Commit struct { - Tree - ID SHA1 // The ID of this commit object - Author *Signature - Committer *Signature - CommitMessage string - Signature *CommitGPGSignature - - parents []SHA1 // SHA1 strings - submoduleCache *ObjectCache -} - -// CommitGPGSignature represents a git commit signature part. -type CommitGPGSignature struct { - Signature string - Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data -} - -// similar to https://github.com/git/git/blob/3bc53220cb2dcf709f7a027a3f526befd021d858/commit.c#L1128 -func newGPGSignatureFromCommitline(data []byte, signatureStart int) (*CommitGPGSignature, error) { - sig := new(CommitGPGSignature) - signatureEnd := bytes.LastIndex(data, []byte("-----END PGP SIGNATURE-----")) - if signatureEnd == -1 { - return nil, fmt.Errorf("end of commit signature not found") - } - sig.Signature = strings.Replace(string(data[signatureStart:signatureEnd+27]), "\n ", "\n", -1) - sig.Payload = string(data[:signatureStart-8]) + string(data[signatureEnd+27:]) - return sig, nil -} - -// Message returns the commit message. Same as retrieving CommitMessage directly. -func (c *Commit) Message() string { - return c.CommitMessage -} - -// Summary returns first line of commit message. -func (c *Commit) Summary() string { - return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0] -} - -// ParentID returns oid of n-th parent (0-based index). -// It returns nil if no such parent exists. -func (c *Commit) ParentID(n int) (SHA1, error) { - if n >= len(c.parents) { - return SHA1{}, ErrNotExist{"", ""} - } - return c.parents[n], nil -} - -// Parent returns n-th parent (0-based index) of the commit. -func (c *Commit) Parent(n int) (*Commit, error) { - id, err := c.ParentID(n) - if err != nil { - return nil, err - } - parent, err := c.repo.getCommit(id) - if err != nil { - return nil, err - } - return parent, nil -} - -// ParentCount returns number of parents of the commit. -// 0 if this is the root commit, otherwise 1,2, etc. -func (c *Commit) ParentCount() int { - return len(c.parents) -} - -func isImageFile(data []byte) (string, bool) { - contentType := http.DetectContentType(data) - if strings.Index(contentType, "image/") != -1 { - return contentType, true - } - return contentType, false -} - -// IsImageFile is a file image type -func (c *Commit) IsImageFile(name string) bool { - blob, err := c.GetBlobByPath(name) - if err != nil { - return false - } - - dataRc, err := blob.DataAsync() - if err != nil { - return false - } - defer dataRc.Close() - buf := make([]byte, 1024) - n, _ := dataRc.Read(buf) - buf = buf[:n] - _, isImage := isImageFile(buf) - return isImage -} - -// GetCommitByPath return the commit of relative path object. -func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) { - return c.repo.getCommitByPathWithID(c.ID, relpath) -} - -// AddChanges marks local changes to be ready for commit. -func AddChanges(repoPath string, all bool, files ...string) error { - cmd := NewCommand("add") - if all { - cmd.AddArguments("--all") - } - _, err := cmd.AddArguments(files...).RunInDir(repoPath) - return err -} - -// CommitChangesOptions the options when a commit created -type CommitChangesOptions struct { - Committer *Signature - Author *Signature - Message string -} - -// CommitChanges commits local changes with given committer, author and message. -// If author is nil, it will be the same as committer. -func CommitChanges(repoPath string, opts CommitChangesOptions) error { - cmd := NewCommand() - if opts.Committer != nil { - cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email) - } - cmd.AddArguments("commit") - - if opts.Author == nil { - opts.Author = opts.Committer - } - if opts.Author != nil { - cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)) - } - cmd.AddArguments("-m", opts.Message) - - _, err := cmd.RunInDir(repoPath) - // No stderr but exit status 1 means nothing to commit. - if err != nil && err.Error() == "exit status 1" { - return nil - } - return err -} - -func commitsCount(repoPath, revision, relpath string) (int64, error) { - var cmd *Command - cmd = NewCommand("rev-list", "--count") - cmd.AddArguments(revision) - if len(relpath) > 0 { - cmd.AddArguments("--", relpath) - } - - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return 0, err - } - - return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) -} - -// CommitsCount returns number of total commits of until given revision. -func CommitsCount(repoPath, revision string) (int64, error) { - return commitsCount(repoPath, revision, "") -} - -// CommitsCount returns number of total commits of until current revision. -func (c *Commit) CommitsCount() (int64, error) { - return CommitsCount(c.repo.Path, c.ID.String()) -} - -// CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize -func (c *Commit) CommitsByRange(page int) (*list.List, error) { - return c.repo.commitsByRange(c.ID, page) -} - -// CommitsBefore returns all the commits before current revision -func (c *Commit) CommitsBefore() (*list.List, error) { - return c.repo.getCommitsBefore(c.ID) -} - -// CommitsBeforeLimit returns num commits before current revision -func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) { - return c.repo.getCommitsBeforeLimit(c.ID, num) -} - -// CommitsBeforeUntil returns the commits between commitID to current revision -func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) { - endCommit, err := c.repo.GetCommit(commitID) - if err != nil { - return nil, err - } - return c.repo.CommitsBetween(c, endCommit) -} - -// SearchCommits returns the commits match the keyword before current revision -func (c *Commit) SearchCommits(keyword string, all bool) (*list.List, error) { - return c.repo.searchCommits(c.ID, keyword, all) -} - -// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision -func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) { - return c.repo.getFilesChanged(pastCommit, c.ID.String()) -} - -// GetSubModules get all the sub modules of current revision git tree -func (c *Commit) GetSubModules() (*ObjectCache, error) { - if c.submoduleCache != nil { - return c.submoduleCache, nil - } - - entry, err := c.GetTreeEntryByPath(".gitmodules") - if err != nil { - if _, ok := err.(ErrNotExist); ok { - return nil, nil - } - return nil, err - } - rd, err := entry.Blob().Data() - if err != nil { - return nil, err - } - - scanner := bufio.NewScanner(rd) - c.submoduleCache = newObjectCache() - var ismodule bool - var path string - for scanner.Scan() { - if strings.HasPrefix(scanner.Text(), "[submodule") { - ismodule = true - continue - } - if ismodule { - fields := strings.Split(scanner.Text(), "=") - k := strings.TrimSpace(fields[0]) - if k == "path" { - path = strings.TrimSpace(fields[1]) - } else if k == "url" { - c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])}) - ismodule = false - } - } - } - - return c.submoduleCache, nil -} - -// GetSubModule get the sub module according entryname -func (c *Commit) GetSubModule(entryname string) (*SubModule, error) { - modules, err := c.GetSubModules() - if err != nil { - return nil, err - } - - if modules != nil { - module, has := modules.Get(entryname) - if has { - return module.(*SubModule), nil - } - } - return nil, nil -} diff --git a/vendor/code.gitea.io/git/commit_archive.go b/vendor/code.gitea.io/git/commit_archive.go deleted file mode 100644 index e13825a96283b..0000000000000 --- a/vendor/code.gitea.io/git/commit_archive.go +++ /dev/null @@ -1,37 +0,0 @@ -// 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 git - -import ( - "fmt" - "path/filepath" - "strings" -) - -// ArchiveType archive types -type ArchiveType int - -const ( - // ZIP zip archive type - ZIP ArchiveType = iota + 1 - // TARGZ tar gz archive type - TARGZ -) - -// CreateArchive create archive content to the target path -func (c *Commit) CreateArchive(target string, archiveType ArchiveType) error { - var format string - switch archiveType { - case ZIP: - format = "zip" - case TARGZ: - format = "tar.gz" - default: - return fmt.Errorf("unknown format: %v", archiveType) - } - - _, err := NewCommand("archive", "--prefix="+filepath.Base(strings.TrimSuffix(c.repo.Path, ".git"))+"/", "--format="+format, "-o", target, c.ID.String()).RunInDir(c.repo.Path) - return err -} diff --git a/vendor/code.gitea.io/git/commit_info.go b/vendor/code.gitea.io/git/commit_info.go deleted file mode 100644 index 6b42b57c90133..0000000000000 --- a/vendor/code.gitea.io/git/commit_info.go +++ /dev/null @@ -1,319 +0,0 @@ -// 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 git - -import ( - "bufio" - "context" - "fmt" - "os/exec" - "path" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -const ( - // parameters for searching for commit infos. If the untargeted search has - // not found any entries in the past 5 commits, and 12 or fewer entries - // remain, then we'll just let the targeted-searching threads finish off, - // and stop the untargeted search to not interfere. - deferToTargetedSearchColdStreak = 5 - deferToTargetedSearchNumRemainingEntries = 12 -) - -// getCommitsInfoState shared state while getting commit info for entries -type getCommitsInfoState struct { - lock sync.Mutex - /* read-only fields, can be read without the mutex */ - // entries and entryPaths are read-only after initialization, so they can - // safely be read without the mutex - entries []*TreeEntry - // set of filepaths to get info for - entryPaths map[string]struct{} - treePath string - headCommit *Commit - - /* mutable fields, must hold mutex to read or write */ - // map from filepath to commit - commits map[string]*Commit - // set of filepaths that have been or are being searched for in a target search - targetedPaths map[string]struct{} -} - -func (state *getCommitsInfoState) numRemainingEntries() int { - state.lock.Lock() - defer state.lock.Unlock() - return len(state.entries) - len(state.commits) -} - -// getTargetEntryPath Returns the next path for a targeted-searching thread to -// search for, or returns the empty string if nothing left to search for -func (state *getCommitsInfoState) getTargetedEntryPath() string { - var targetedEntryPath string - state.lock.Lock() - defer state.lock.Unlock() - for _, entry := range state.entries { - entryPath := path.Join(state.treePath, entry.Name()) - if _, ok := state.commits[entryPath]; ok { - continue - } else if _, ok = state.targetedPaths[entryPath]; ok { - continue - } - targetedEntryPath = entryPath - state.targetedPaths[entryPath] = struct{}{} - break - } - return targetedEntryPath -} - -// repeatedly perform targeted searches for unpopulated entries -func targetedSearch(state *getCommitsInfoState, done chan error) { - for { - entryPath := state.getTargetedEntryPath() - if len(entryPath) == 0 { - done <- nil - return - } - command := NewCommand("rev-list", "-1", state.headCommit.ID.String(), "--", entryPath) - output, err := command.RunInDir(state.headCommit.repo.Path) - if err != nil { - done <- err - return - } - id, err := NewIDFromString(strings.TrimSpace(output)) - if err != nil { - done <- err - return - } - commit, err := state.headCommit.repo.getCommit(id) - if err != nil { - done <- err - return - } - state.update(entryPath, commit) - } -} - -func initGetCommitInfoState(entries Entries, headCommit *Commit, treePath string) *getCommitsInfoState { - entryPaths := make(map[string]struct{}, len(entries)) - for _, entry := range entries { - entryPaths[path.Join(treePath, entry.Name())] = struct{}{} - } - if treePath = path.Clean(treePath); treePath == "." { - treePath = "" - } - return &getCommitsInfoState{ - entries: entries, - entryPaths: entryPaths, - commits: make(map[string]*Commit, len(entries)), - targetedPaths: make(map[string]struct{}, len(entries)), - treePath: treePath, - headCommit: headCommit, - } -} - -// GetCommitsInfo gets information of all commits that are corresponding to these entries -func (tes Entries) GetCommitsInfo(commit *Commit, treePath string) ([][]interface{}, error) { - state := initGetCommitInfoState(tes, commit, treePath) - if err := getCommitsInfo(state); err != nil { - return nil, err - } - if len(state.commits) < len(state.entryPaths) { - return nil, fmt.Errorf("could not find commits for all entries") - } - - commitsInfo := make([][]interface{}, len(tes)) - for i, entry := range tes { - commit, ok := state.commits[path.Join(treePath, entry.Name())] - if !ok { - return nil, fmt.Errorf("could not find commit for %s", entry.Name()) - } - switch entry.Type { - case ObjectCommit: - subModuleURL := "" - if subModule, err := state.headCommit.GetSubModule(entry.Name()); err != nil { - return nil, err - } else if subModule != nil { - subModuleURL = subModule.URL - } - subModuleFile := NewSubModuleFile(commit, subModuleURL, entry.ID.String()) - commitsInfo[i] = []interface{}{entry, subModuleFile} - default: - commitsInfo[i] = []interface{}{entry, commit} - } - } - return commitsInfo, nil -} - -func (state *getCommitsInfoState) cleanEntryPath(rawEntryPath string) (string, error) { - if rawEntryPath[0] == '"' { - var err error - rawEntryPath, err = strconv.Unquote(rawEntryPath) - if err != nil { - return rawEntryPath, err - } - } - var entryNameStartIndex int - if len(state.treePath) > 0 { - entryNameStartIndex = len(state.treePath) + 1 - } - - if index := strings.IndexByte(rawEntryPath[entryNameStartIndex:], '/'); index >= 0 { - return rawEntryPath[:entryNameStartIndex+index], nil - } - return rawEntryPath, nil -} - -// update report that the given path was last modified by the given commit. -// Returns whether state.commits was updated -func (state *getCommitsInfoState) update(entryPath string, commit *Commit) bool { - if _, ok := state.entryPaths[entryPath]; !ok { - return false - } - - var updated bool - state.lock.Lock() - defer state.lock.Unlock() - if _, ok := state.commits[entryPath]; !ok { - state.commits[entryPath] = commit - updated = true - } - return updated -} - -const getCommitsInfoPretty = "--pretty=format:%H %ct %s" - -func getCommitsInfo(state *getCommitsInfoState) error { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) - defer cancel() - - args := []string{"log", state.headCommit.ID.String(), getCommitsInfoPretty, "--name-status", "-c"} - if len(state.treePath) > 0 { - args = append(args, "--", state.treePath) - } - cmd := exec.CommandContext(ctx, "git", args...) - cmd.Dir = state.headCommit.repo.Path - - readCloser, err := cmd.StdoutPipe() - if err != nil { - return err - } - - if err := cmd.Start(); err != nil { - return err - } - // it's okay to ignore the error returned by cmd.Wait(); we expect the - // subprocess to sometimes have a non-zero exit status, since we may - // prematurely close stdout, resulting in a broken pipe. - defer cmd.Wait() - - numThreads := runtime.NumCPU() - done := make(chan error, numThreads) - for i := 0; i < numThreads; i++ { - go targetedSearch(state, done) - } - - scanner := bufio.NewScanner(readCloser) - err = state.processGitLogOutput(scanner) - - // it is important that we close stdout here; if we do not close - // stdout, the subprocess will keep running, and the deffered call - // cmd.Wait() may block for a long time. - if closeErr := readCloser.Close(); closeErr != nil && err == nil { - err = closeErr - } - - for i := 0; i < numThreads; i++ { - doneErr := <-done - if doneErr != nil && err == nil { - err = doneErr - } - } - return err -} - -func (state *getCommitsInfoState) processGitLogOutput(scanner *bufio.Scanner) error { - // keep a local cache of seen paths to avoid acquiring a lock for paths - // we've already seen - seenPaths := make(map[string]struct{}, len(state.entryPaths)) - // number of consecutive commits without any finds - coldStreak := 0 - var commit *Commit - var err error - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 { // in-between commits - numRemainingEntries := state.numRemainingEntries() - if numRemainingEntries == 0 { - break - } - if coldStreak >= deferToTargetedSearchColdStreak && - numRemainingEntries <= deferToTargetedSearchNumRemainingEntries { - // stop this untargeted search, and let the targeted-search threads - // finish the work - break - } - continue - } - if line[0] >= 'A' && line[0] <= 'X' { // a file was changed by the current commit - // look for the last tab, since for copies (C) and renames (R) two - // filenames are printed: src, then dest - tabIndex := strings.LastIndexByte(line, '\t') - if tabIndex < 1 { - return fmt.Errorf("misformatted line: %s", line) - } - entryPath, err := state.cleanEntryPath(line[tabIndex+1:]) - if err != nil { - return err - } - if _, ok := seenPaths[entryPath]; !ok { - if state.update(entryPath, commit) { - coldStreak = 0 - } - seenPaths[entryPath] = struct{}{} - } - continue - } - - // a new commit - commit, err = parseCommitInfo(line) - if err != nil { - return err - } - coldStreak++ - } - return scanner.Err() -} - -// parseCommitInfo parse a commit from a line of `git log` output. Expects the -// line to be formatted according to getCommitsInfoPretty. -func parseCommitInfo(line string) (*Commit, error) { - if len(line) < 43 { - return nil, fmt.Errorf("invalid git output: %s", line) - } - ref, err := NewIDFromString(line[:40]) - if err != nil { - return nil, err - } - spaceIndex := strings.IndexByte(line[41:], ' ') - if spaceIndex < 0 { - return nil, fmt.Errorf("invalid git output: %s", line) - } - unixSeconds, err := strconv.Atoi(line[41 : 41+spaceIndex]) - if err != nil { - return nil, err - } - message := line[spaceIndex+42:] - return &Commit{ - ID: ref, - CommitMessage: message, - Committer: &Signature{ - When: time.Unix(int64(unixSeconds), 0), - }, - }, nil -} diff --git a/vendor/code.gitea.io/git/doc.go b/vendor/code.gitea.io/git/doc.go deleted file mode 100644 index 1941d285507b1..0000000000000 --- a/vendor/code.gitea.io/git/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// 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 git // import "code.gitea.io/git" diff --git a/vendor/code.gitea.io/git/error.go b/vendor/code.gitea.io/git/error.go deleted file mode 100644 index 1aae5a37a2891..0000000000000 --- a/vendor/code.gitea.io/git/error.go +++ /dev/null @@ -1,66 +0,0 @@ -// 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 git - -import ( - "fmt" - "time" -) - -// ErrExecTimeout error when exec timed out -type ErrExecTimeout struct { - Duration time.Duration -} - -// IsErrExecTimeout if some error is ErrExecTimeout -func IsErrExecTimeout(err error) bool { - _, ok := err.(ErrExecTimeout) - return ok -} - -func (err ErrExecTimeout) Error() string { - return fmt.Sprintf("execution is timeout [duration: %v]", err.Duration) -} - -// ErrNotExist commit not exist error -type ErrNotExist struct { - ID string - RelPath string -} - -// IsErrNotExist if some error is ErrNotExist -func IsErrNotExist(err error) bool { - _, ok := err.(ErrNotExist) - return ok -} - -func (err ErrNotExist) Error() string { - return fmt.Sprintf("object does not exist [id: %s, rel_path: %s]", err.ID, err.RelPath) -} - -// ErrBadLink entry.FollowLink error -type ErrBadLink struct { - Name string - Message string -} - -func (err ErrBadLink) Error() string { - return fmt.Sprintf("%s: %s", err.Name, err.Message) -} - -// ErrUnsupportedVersion error when required git version not matched -type ErrUnsupportedVersion struct { - Required string -} - -// IsErrUnsupportedVersion if some error is ErrUnsupportedVersion -func IsErrUnsupportedVersion(err error) bool { - _, ok := err.(ErrUnsupportedVersion) - return ok -} - -func (err ErrUnsupportedVersion) Error() string { - return fmt.Sprintf("Operation requires higher version [required: %s]", err.Required) -} diff --git a/vendor/code.gitea.io/git/git.go b/vendor/code.gitea.io/git/git.go deleted file mode 100644 index 150b80fb076b8..0000000000000 --- a/vendor/code.gitea.io/git/git.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2015 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 git - -import ( - "fmt" - "strings" - "time" - - "github.com/mcuadros/go-version" -) - -// Version return this package's current version -func Version() string { - return "0.4.2" -} - -var ( - // Debug enables verbose logging on everything. - // This should be false in case Gogs starts in SSH mode. - Debug = false - // Prefix the log prefix - Prefix = "[git-module] " - // GitVersionRequired is the minimum Git version required - GitVersionRequired = "1.7.2" -) - -func log(format string, args ...interface{}) { - if !Debug { - return - } - - fmt.Print(Prefix) - if len(args) == 0 { - fmt.Println(format) - } else { - fmt.Printf(format+"\n", args...) - } -} - -var gitVersion string - -// BinVersion returns current Git version from shell. -func BinVersion() (string, error) { - if len(gitVersion) > 0 { - return gitVersion, nil - } - - stdout, err := NewCommand("version").Run() - if err != nil { - return "", err - } - - fields := strings.Fields(stdout) - if len(fields) < 3 { - return "", fmt.Errorf("not enough output: %s", stdout) - } - - // Handle special case on Windows. - i := strings.Index(fields[2], "windows") - if i >= 1 { - gitVersion = fields[2][:i-1] - return gitVersion, nil - } - - gitVersion = fields[2] - return gitVersion, nil -} - -func init() { - gitVersion, err := BinVersion() - if err != nil { - panic(fmt.Sprintf("Git version missing: %v", err)) - } - if version.Compare(gitVersion, GitVersionRequired, "<") { - panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired)) - } -} - -// Fsck verifies the connectivity and validity of the objects in the database -func Fsck(repoPath string, timeout time.Duration, args ...string) error { - // Make sure timeout makes sense. - if timeout <= 0 { - timeout = -1 - } - _, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) - return err -} diff --git a/vendor/code.gitea.io/git/hook.go b/vendor/code.gitea.io/git/hook.go deleted file mode 100644 index afed623e6eacf..0000000000000 --- a/vendor/code.gitea.io/git/hook.go +++ /dev/null @@ -1,126 +0,0 @@ -// 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 git - -import ( - "errors" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - - "github.com/Unknwon/com" -) - -// hookNames is a list of Git server hooks' name that are supported. -var hookNames = []string{ - "pre-receive", - "update", - "post-receive", -} - -var ( - // ErrNotValidHook error when a git hook is not valid - ErrNotValidHook = errors.New("not a valid Git hook") -) - -// IsValidHookName returns true if given name is a valid Git hook. -func IsValidHookName(name string) bool { - for _, hn := range hookNames { - if hn == name { - return true - } - } - return false -} - -// Hook represents a Git hook. -type Hook struct { - name string - IsActive bool // Indicates whether repository has this hook. - Content string // Content of hook if it's active. - Sample string // Sample content from Git. - path string // Hook file path. -} - -// GetHook returns a Git hook by given name and repository. -func GetHook(repoPath, name string) (*Hook, error) { - if !IsValidHookName(name) { - return nil, ErrNotValidHook - } - h := &Hook{ - name: name, - path: path.Join(repoPath, "hooks", name+".d", name), - } - samplePath := filepath.Join(repoPath, "hooks", name+".sample") - if isFile(h.path) { - data, err := ioutil.ReadFile(h.path) - if err != nil { - return nil, err - } - h.IsActive = true - h.Content = string(data) - } else if isFile(samplePath) { - data, err := ioutil.ReadFile(samplePath) - if err != nil { - return nil, err - } - h.Sample = string(data) - } - return h, nil -} - -// Name return the name of the hook -func (h *Hook) Name() string { - return h.name -} - -// Update updates hook settings. -func (h *Hook) Update() error { - if len(strings.TrimSpace(h.Content)) == 0 { - if isExist(h.path) { - return os.Remove(h.path) - } - return nil - } - return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm) -} - -// ListHooks returns a list of Git hooks of given repository. -func ListHooks(repoPath string) (_ []*Hook, err error) { - if !isDir(path.Join(repoPath, "hooks")) { - return nil, errors.New("hooks path does not exist") - } - - hooks := make([]*Hook, len(hookNames)) - for i, name := range hookNames { - hooks[i], err = GetHook(repoPath, name) - if err != nil { - return nil, err - } - } - return hooks, nil -} - -const ( - // HookPathUpdate hook update path - HookPathUpdate = "hooks/update" -) - -// SetUpdateHook writes given content to update hook of the reposiotry. -func SetUpdateHook(repoPath, content string) (err error) { - log("Setting update hook: %s", repoPath) - hookPath := path.Join(repoPath, HookPathUpdate) - if com.IsExist(hookPath) { - err = os.Remove(hookPath) - } else { - err = os.MkdirAll(path.Dir(hookPath), os.ModePerm) - } - if err != nil { - return err - } - return ioutil.WriteFile(hookPath, []byte(content), 0777) -} diff --git a/vendor/code.gitea.io/git/parse.go b/vendor/code.gitea.io/git/parse.go deleted file mode 100644 index 5c964f16ee5f7..0000000000000 --- a/vendor/code.gitea.io/git/parse.go +++ /dev/null @@ -1,81 +0,0 @@ -// 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 git - -import ( - "bytes" - "fmt" - "strconv" -) - -// ParseTreeEntries parses the output of a `git ls-tree` command. -func ParseTreeEntries(data []byte) ([]*TreeEntry, error) { - return parseTreeEntries(data, nil) -} - -func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) { - entries := make([]*TreeEntry, 0, 10) - for pos := 0; pos < len(data); { - // expect line to be of the form " \t" - entry := new(TreeEntry) - entry.ptree = ptree - if pos+6 > len(data) { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - switch string(data[pos : pos+6]) { - case "100644": - entry.mode = EntryModeBlob - entry.Type = ObjectBlob - pos += 12 // skip over "100644 blob " - case "100755": - entry.mode = EntryModeExec - entry.Type = ObjectBlob - pos += 12 // skip over "100755 blob " - case "120000": - entry.mode = EntryModeSymlink - entry.Type = ObjectBlob - pos += 12 // skip over "120000 blob " - case "160000": - entry.mode = EntryModeCommit - entry.Type = ObjectCommit - pos += 14 // skip over "160000 object " - case "040000": - entry.mode = EntryModeTree - entry.Type = ObjectTree - pos += 12 // skip over "040000 tree " - default: - return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6])) - } - - if pos+40 > len(data) { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - id, err := NewIDFromString(string(data[pos : pos+40])) - if err != nil { - return nil, fmt.Errorf("Invalid ls-tree output: %v", err) - } - entry.ID = id - pos += 41 // skip over sha and trailing space - - end := pos + bytes.IndexByte(data[pos:], '\n') - if end < pos { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - - // In case entry name is surrounded by double quotes(it happens only in git-shell). - if data[pos] == '"' { - entry.name, err = strconv.Unquote(string(data[pos:end])) - if err != nil { - return nil, fmt.Errorf("Invalid ls-tree output: %v", err) - } - } else { - entry.name = string(data[pos:end]) - } - - pos = end + 1 - entries = append(entries, entry) - } - return entries, nil -} diff --git a/vendor/code.gitea.io/git/repo.go b/vendor/code.gitea.io/git/repo.go deleted file mode 100644 index 4306730920eb2..0000000000000 --- a/vendor/code.gitea.io/git/repo.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2015 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 git - -import ( - "bytes" - "container/list" - "errors" - "os" - "path" - "path/filepath" - "strings" - "time" - - "github.com/Unknwon/com" -) - -// Repository represents a Git repository. -type Repository struct { - Path string - - commitCache *ObjectCache - tagCache *ObjectCache -} - -const prettyLogFormat = `--pretty=format:%H` - -func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) { - l := list.New() - if len(logs) == 0 { - return l, nil - } - - parts := bytes.Split(logs, []byte{'\n'}) - - for _, commitID := range parts { - commit, err := repo.GetCommit(string(commitID)) - if err != nil { - return nil, err - } - l.PushBack(commit) - } - - return l, nil -} - -// IsRepoURLAccessible checks if given repository URL is accessible. -func IsRepoURLAccessible(url string) bool { - _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run() - if err != nil { - return false - } - return true -} - -// InitRepository initializes a new Git repository. -func InitRepository(repoPath string, bare bool) error { - os.MkdirAll(repoPath, os.ModePerm) - - cmd := NewCommand("init") - if bare { - cmd.AddArguments("--bare") - } - _, err := cmd.RunInDir(repoPath) - return err -} - -// OpenRepository opens the repository at the given path. -func OpenRepository(repoPath string) (*Repository, error) { - repoPath, err := filepath.Abs(repoPath) - if err != nil { - return nil, err - } else if !isDir(repoPath) { - return nil, errors.New("no such file or directory") - } - - return &Repository{ - Path: repoPath, - commitCache: newObjectCache(), - tagCache: newObjectCache(), - }, nil -} - -// CloneRepoOptions options when clone a repository -type CloneRepoOptions struct { - Timeout time.Duration - Mirror bool - Bare bool - Quiet bool - Branch string -} - -// Clone clones original repository to target path. -func Clone(from, to string, opts CloneRepoOptions) (err error) { - toDir := path.Dir(to) - if err = os.MkdirAll(toDir, os.ModePerm); err != nil { - return err - } - - cmd := NewCommand("clone") - if opts.Mirror { - cmd.AddArguments("--mirror") - } - if opts.Bare { - cmd.AddArguments("--bare") - } - if opts.Quiet { - cmd.AddArguments("--quiet") - } - if len(opts.Branch) > 0 { - cmd.AddArguments("-b", opts.Branch) - } - cmd.AddArguments(from, to) - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - _, err = cmd.RunTimeout(opts.Timeout) - return err -} - -// PullRemoteOptions options when pull from remote -type PullRemoteOptions struct { - Timeout time.Duration - All bool - Rebase bool - Remote string - Branch string -} - -// Pull pulls changes from remotes. -func Pull(repoPath string, opts PullRemoteOptions) error { - cmd := NewCommand("pull") - if opts.Rebase { - cmd.AddArguments("--rebase") - } - if opts.All { - cmd.AddArguments("--all") - } else { - cmd.AddArguments(opts.Remote) - cmd.AddArguments(opts.Branch) - } - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) - return err -} - -// PushOptions options when push to remote -type PushOptions struct { - Remote string - Branch string - Force bool -} - -// Push pushs local commits to given remote branch. -func Push(repoPath string, opts PushOptions) error { - cmd := NewCommand("push") - if opts.Force { - cmd.AddArguments("-f") - } - cmd.AddArguments(opts.Remote, opts.Branch) - _, err := cmd.RunInDir(repoPath) - return err -} - -// CheckoutOptions options when heck out some branch -type CheckoutOptions struct { - Timeout time.Duration - Branch string - OldBranch string -} - -// Checkout checkouts a branch -func Checkout(repoPath string, opts CheckoutOptions) error { - cmd := NewCommand("checkout") - if len(opts.OldBranch) > 0 { - cmd.AddArguments("-b") - } - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - cmd.AddArguments(opts.Branch) - - if len(opts.OldBranch) > 0 { - cmd.AddArguments(opts.OldBranch) - } - - _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) - return err -} - -// ResetHEAD resets HEAD to given revision or head of branch. -func ResetHEAD(repoPath string, hard bool, revision string) error { - cmd := NewCommand("reset") - if hard { - cmd.AddArguments("--hard") - } - _, err := cmd.AddArguments(revision).RunInDir(repoPath) - return err -} - -// MoveFile moves a file to another file or directory. -func MoveFile(repoPath, oldTreeName, newTreeName string) error { - _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath) - return err -} - -// CountObject represents repository count objects report -type CountObject struct { - Count int64 - Size int64 - InPack int64 - Packs int64 - SizePack int64 - PrunePack int64 - Garbage int64 - SizeGarbage int64 -} - -const ( - statCount = "count: " - statSize = "size: " - statInpack = "in-pack: " - statPacks = "packs: " - statSizePack = "size-pack: " - statPrunePackage = "prune-package: " - statGarbage = "garbage: " - statSizeGarbage = "size-garbage: " -) - -// GetRepoSize returns disk consumption for repo in path -func GetRepoSize(repoPath string) (*CountObject, error) { - cmd := NewCommand("count-objects", "-v") - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return nil, err - } - - return parseSize(stdout), nil -} - -// parseSize parses the output from count-objects and return a CountObject -func parseSize(objects string) *CountObject { - repoSize := new(CountObject) - for _, line := range strings.Split(objects, "\n") { - switch { - case strings.HasPrefix(line, statCount): - repoSize.Count = com.StrTo(line[7:]).MustInt64() - case strings.HasPrefix(line, statSize): - repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024 - case strings.HasPrefix(line, statInpack): - repoSize.InPack = com.StrTo(line[9:]).MustInt64() - case strings.HasPrefix(line, statPacks): - repoSize.Packs = com.StrTo(line[7:]).MustInt64() - case strings.HasPrefix(line, statSizePack): - repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024 - case strings.HasPrefix(line, statPrunePackage): - repoSize.PrunePack = com.StrTo(line[16:]).MustInt64() - case strings.HasPrefix(line, statGarbage): - repoSize.Garbage = com.StrTo(line[9:]).MustInt64() - case strings.HasPrefix(line, statSizeGarbage): - repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024 - } - } - return repoSize -} - -// GetLatestCommitTime returns time for latest commit in repository (across all branches) -func GetLatestCommitTime(repoPath string) (time.Time, error) { - cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)") - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return time.Time{}, err - } - commitTime := strings.TrimSpace(stdout) - return time.Parse(GitTimeLayout, commitTime) -} diff --git a/vendor/code.gitea.io/git/repo_blame.go b/vendor/code.gitea.io/git/repo_blame.go deleted file mode 100644 index 80ec50e4723cf..0000000000000 --- a/vendor/code.gitea.io/git/repo_blame.go +++ /dev/null @@ -1,24 +0,0 @@ -// 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 git - -import "fmt" - -// FileBlame return the Blame object of file -func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { - return NewCommand("blame", "--root", "--", file).RunInDirBytes(path) -} - -// LineBlame returns the latest commit at the given line -func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { - res, err := NewCommand("blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) - if err != nil { - return nil, err - } - if len(res) < 40 { - return nil, fmt.Errorf("invalid result of blame: %s", res) - } - return repo.GetCommit(string(res[:40])) -} diff --git a/vendor/code.gitea.io/git/repo_branch.go b/vendor/code.gitea.io/git/repo_branch.go deleted file mode 100644 index 3b50eece14a31..0000000000000 --- a/vendor/code.gitea.io/git/repo_branch.go +++ /dev/null @@ -1,123 +0,0 @@ -// 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 git - -import ( - "fmt" - "strings" -) - -// BranchPrefix base dir of the branch information file store on git -const BranchPrefix = "refs/heads/" - -// IsReferenceExist returns true if given reference exists in the repository. -func IsReferenceExist(repoPath, name string) bool { - _, err := NewCommand("show-ref", "--verify", name).RunInDir(repoPath) - return err == nil -} - -// IsBranchExist returns true if given branch exists in the repository. -func IsBranchExist(repoPath, name string) bool { - return IsReferenceExist(repoPath, BranchPrefix+name) -} - -// IsBranchExist returns true if given branch exists in current repository. -func (repo *Repository) IsBranchExist(name string) bool { - return IsBranchExist(repo.Path, name) -} - -// Branch represents a Git branch. -type Branch struct { - Name string - Path string -} - -// GetHEADBranch returns corresponding branch of HEAD. -func (repo *Repository) GetHEADBranch() (*Branch, error) { - stdout, err := NewCommand("symbolic-ref", "HEAD").RunInDir(repo.Path) - if err != nil { - return nil, err - } - stdout = strings.TrimSpace(stdout) - - if !strings.HasPrefix(stdout, BranchPrefix) { - return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) - } - - return &Branch{ - Name: stdout[len(BranchPrefix):], - Path: stdout, - }, nil -} - -// SetDefaultBranch sets default branch of repository. -func (repo *Repository) SetDefaultBranch(name string) error { - _, err := NewCommand("symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) - return err -} - -// GetBranches returns all branches of the repository. -func (repo *Repository) GetBranches() ([]string, error) { - stdout, err := NewCommand("for-each-ref", "--format=%(refname)", BranchPrefix).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - refs := strings.Split(stdout, "\n") - branches := make([]string, len(refs)-1) - for i, ref := range refs[:len(refs)-1] { - branches[i] = strings.TrimPrefix(ref, BranchPrefix) - } - return branches, nil -} - -// DeleteBranchOptions Option(s) for delete branch -type DeleteBranchOptions struct { - Force bool -} - -// DeleteBranch delete a branch by name on repository. -func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { - cmd := NewCommand("branch") - - if opts.Force { - cmd.AddArguments("-D") - } else { - cmd.AddArguments("-d") - } - - cmd.AddArguments(name) - _, err := cmd.RunInDir(repo.Path) - - return err -} - -// CreateBranch create a new branch -func (repo *Repository) CreateBranch(branch, newBranch string) error { - cmd := NewCommand("branch") - cmd.AddArguments(branch, newBranch) - - _, err := cmd.RunInDir(repo.Path) - - return err -} - -// AddRemote adds a new remote to repository. -func (repo *Repository) AddRemote(name, url string, fetch bool) error { - cmd := NewCommand("remote", "add") - if fetch { - cmd.AddArguments("-f") - } - cmd.AddArguments(name, url) - - _, err := cmd.RunInDir(repo.Path) - return err -} - -// RemoveRemote removes a remote from repository. -func (repo *Repository) RemoveRemote(name string) error { - _, err := NewCommand("remote", "remove", name).RunInDir(repo.Path) - return err -} diff --git a/vendor/code.gitea.io/git/repo_commit.go b/vendor/code.gitea.io/git/repo_commit.go deleted file mode 100644 index 1acdfffb34738..0000000000000 --- a/vendor/code.gitea.io/git/repo_commit.go +++ /dev/null @@ -1,352 +0,0 @@ -// 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 git - -import ( - "bytes" - "container/list" - "strconv" - "strings" - - "github.com/mcuadros/go-version" -) - -// GetRefCommitID returns the last commit ID string of given reference (branch or tag). -func (repo *Repository) GetRefCommitID(name string) (string, error) { - stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path) - if err != nil { - if strings.Contains(err.Error(), "not a valid ref") { - return "", ErrNotExist{name, ""} - } - return "", err - } - return strings.Split(stdout, " ")[0], nil -} - -// GetBranchCommitID returns last commit ID string of given branch. -func (repo *Repository) GetBranchCommitID(name string) (string, error) { - return repo.GetRefCommitID(BranchPrefix + name) -} - -// GetTagCommitID returns last commit ID string of given tag. -func (repo *Repository) GetTagCommitID(name string) (string, error) { - return repo.GetRefCommitID(TagPrefix + name) -} - -// parseCommitData parses commit information from the (uncompressed) raw -// data from the commit object. -// \n\n separate headers from message -func parseCommitData(data []byte) (*Commit, error) { - commit := new(Commit) - commit.parents = make([]SHA1, 0, 1) - // we now have the contents of the commit object. Let's investigate... - nextline := 0 -l: - for { - eol := bytes.IndexByte(data[nextline:], '\n') - switch { - case eol > 0: - line := data[nextline : nextline+eol] - spacepos := bytes.IndexByte(line, ' ') - reftype := line[:spacepos] - switch string(reftype) { - case "tree", "object": - id, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - commit.Tree.ID = id - case "parent": - // A commit can have one or more parents - oid, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - commit.parents = append(commit.parents, oid) - case "author", "tagger": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - commit.Author = sig - case "committer": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - commit.Committer = sig - case "gpgsig": - sig, err := newGPGSignatureFromCommitline(data, nextline+spacepos+1) - if err != nil { - return nil, err - } - commit.Signature = sig - } - nextline += eol + 1 - case eol == 0: - commit.CommitMessage = string(data[nextline+1:]) - break l - default: - break l - } - } - return commit, nil -} - -func (repo *Repository) getCommit(id SHA1) (*Commit, error) { - c, ok := repo.commitCache.Get(id.String()) - if ok { - log("Hit cache: %s", id) - return c.(*Commit), nil - } - - data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) - if err != nil { - if strings.Contains(err.Error(), "fatal: Not a valid object name") { - return nil, ErrNotExist{id.String(), ""} - } - return nil, err - } - - commit, err := parseCommitData(data) - if err != nil { - return nil, err - } - commit.repo = repo - commit.ID = id - - repo.commitCache.Set(id.String(), commit) - return commit, nil -} - -// GetCommit returns commit object of by ID string. -func (repo *Repository) GetCommit(commitID string) (*Commit, error) { - if len(commitID) != 40 { - var err error - commitID, err = NewCommand("rev-parse", commitID).RunInDir(repo.Path) - if err != nil { - return nil, err - } - } - id, err := NewIDFromString(commitID) - if err != nil { - return nil, err - } - - return repo.getCommit(id) -} - -// GetBranchCommit returns the last commit of given branch. -func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { - commitID, err := repo.GetBranchCommitID(name) - if err != nil { - return nil, err - } - return repo.GetCommit(commitID) -} - -// GetTagCommit get the commit of the specific tag via name -func (repo *Repository) GetTagCommit(name string) (*Commit, error) { - commitID, err := repo.GetTagCommitID(name) - if err != nil { - return nil, err - } - return repo.GetCommit(commitID) -} - -func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) { - // File name starts with ':' must be escaped. - if relpath[0] == ':' { - relpath = `\` + relpath - } - - stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - id, err = NewIDFromString(stdout) - if err != nil { - return nil, err - } - - return repo.getCommit(id) -} - -// GetCommitByPath returns the last commit of relative path. -func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { - stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - commits, err := repo.parsePrettyFormatLogToList(stdout) - if err != nil { - return nil, err - } - return commits.Front().Value.(*Commit), nil -} - -// CommitsRangeSize the default commits range size -var CommitsRangeSize = 50 - -func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) { - stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize), - "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -func (repo *Repository) searchCommits(id SHA1, keyword string, all bool) (*list.List, error) { - cmd := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, prettyLogFormat) - if all { - cmd.AddArguments("--all") - } - stdout, err := cmd.RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) { - stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return strings.Split(string(stdout), "\n"), nil -} - -// FileCommitsCount return the number of files at a revison -func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) { - return commitsCount(repo.Path, revision, file) -} - -// CommitsByFileAndRange return the commits accroding revison file and the page -func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) { - stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50), - "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -// FilesCountBetween return the number of files changed between two commits -func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { - stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) - if err != nil { - return 0, err - } - return len(strings.Split(stdout, "\n")) - 1, nil -} - -// CommitsBetween returns a list that contains commits between [last, before). -func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { - stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) -} - -// CommitsBetweenIDs return commits between twoe commits -func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) { - lastCommit, err := repo.GetCommit(last) - if err != nil { - return nil, err - } - beforeCommit, err := repo.GetCommit(before) - if err != nil { - return nil, err - } - return repo.CommitsBetween(lastCommit, beforeCommit) -} - -// CommitsCountBetween return numbers of commits between two commits -func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) { - return commitsCount(repo.Path, start+"..."+end, "") -} - -// commitsBefore the limit is depth, not total number of returned commits. -func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) { - cmd := NewCommand("log") - if limit > 0 { - cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String()) - } else { - cmd.AddArguments(prettyLogFormat, id.String()) - } - - stdout, err := cmd.RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) - if err != nil { - return nil, err - } - - commits := list.New() - for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() { - commit := logEntry.Value.(*Commit) - branches, err := repo.getBranches(commit, 2) - if err != nil { - return nil, err - } - - if len(branches) > 1 { - break - } - - commits.PushBack(commit) - } - - return commits, nil -} - -func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) { - return repo.commitsBefore(id, 0) -} - -func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) { - return repo.commitsBefore(id, num) -} - -func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { - if version.Compare(gitVersion, "2.7.0", ">=") { - stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - branches := strings.Fields(stdout) - return branches, nil - } - - stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - refs := strings.Split(stdout, "\n") - - var max int - if len(refs) > limit { - max = limit - } else { - max = len(refs) - 1 - } - - branches := make([]string, max) - for i, ref := range refs[:max] { - parts := strings.Fields(ref) - - branches[i] = parts[len(parts)-1] - } - return branches, nil -} diff --git a/vendor/code.gitea.io/git/repo_hook.go b/vendor/code.gitea.io/git/repo_hook.go deleted file mode 100644 index 49f4d09fb685b..0000000000000 --- a/vendor/code.gitea.io/git/repo_hook.go +++ /dev/null @@ -1,15 +0,0 @@ -// 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 git - -// GetHook get one hook accroding the name on a repository -func (repo *Repository) GetHook(name string) (*Hook, error) { - return GetHook(repo.Path, name) -} - -// Hooks get all the hooks on the repository -func (repo *Repository) Hooks() ([]*Hook, error) { - return ListHooks(repo.Path) -} diff --git a/vendor/code.gitea.io/git/repo_object.go b/vendor/code.gitea.io/git/repo_object.go deleted file mode 100644 index 3be8400d22210..0000000000000 --- a/vendor/code.gitea.io/git/repo_object.go +++ /dev/null @@ -1,19 +0,0 @@ -// 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 git - -// ObjectType git object type -type ObjectType string - -const ( - // ObjectCommit commit object type - ObjectCommit ObjectType = "commit" - // ObjectTree tree object type - ObjectTree ObjectType = "tree" - // ObjectBlob blob object type - ObjectBlob ObjectType = "blob" - // ObjectTag tag object type - ObjectTag ObjectType = "tag" -) diff --git a/vendor/code.gitea.io/git/repo_pull.go b/vendor/code.gitea.io/git/repo_pull.go deleted file mode 100644 index c6d97a6fd167d..0000000000000 --- a/vendor/code.gitea.io/git/repo_pull.go +++ /dev/null @@ -1,89 +0,0 @@ -// 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 git - -import ( - "bytes" - "container/list" - "fmt" - "io" - "strconv" - "strings" - "time" -) - -// PullRequestInfo represents needed information for a pull request. -type PullRequestInfo struct { - MergeBase string - Commits *list.List - NumFiles int -} - -// GetMergeBase checks and returns merge base of two branches. -func (repo *Repository) GetMergeBase(base, head string) (string, error) { - stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path) - return strings.TrimSpace(stdout), err -} - -// GetPullRequestInfo generates and returns pull request information -// between base and head branches of repositories. -func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) { - var remoteBranch string - - // We don't need a temporary remote for same repository. - if repo.Path != basePath { - // Add a temporary remote - tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) - if err = repo.AddRemote(tmpRemote, basePath, true); err != nil { - return nil, fmt.Errorf("AddRemote: %v", err) - } - defer repo.RemoveRemote(tmpRemote) - - remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch - } else { - remoteBranch = baseBranch - } - - prInfo := new(PullRequestInfo) - prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch) - if err != nil { - return nil, fmt.Errorf("GetMergeBase: %v", err) - } - - logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs) - if err != nil { - return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err) - } - - // Count number of changed files. - stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path) - if err != nil { - return nil, err - } - prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1 - - return prInfo, nil -} - -// GetPatch generates and returns patch data between given revisions. -func (repo *Repository) GetPatch(base, head string) ([]byte, error) { - return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path) -} - -// GetFormatPatch generates and returns format-patch data between given revisions. -func (repo *Repository) GetFormatPatch(base, head string) (io.Reader, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - - if err := NewCommand("format-patch", "--binary", "--stdout", base+"..."+head). - RunInDirPipeline(repo.Path, stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - return stdout, nil -} diff --git a/vendor/code.gitea.io/git/repo_tag.go b/vendor/code.gitea.io/git/repo_tag.go deleted file mode 100644 index 11f1f3da73af9..0000000000000 --- a/vendor/code.gitea.io/git/repo_tag.go +++ /dev/null @@ -1,157 +0,0 @@ -// 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 git - -import ( - "strings" - - "github.com/mcuadros/go-version" -) - -// TagPrefix tags prefix path on the repository -const TagPrefix = "refs/tags/" - -// IsTagExist returns true if given tag exists in the repository. -func IsTagExist(repoPath, name string) bool { - return IsReferenceExist(repoPath, TagPrefix+name) -} - -// IsTagExist returns true if given tag exists in the repository. -func (repo *Repository) IsTagExist(name string) bool { - return IsTagExist(repo.Path, name) -} - -// CreateTag create one tag in the repository -func (repo *Repository) CreateTag(name, revision string) error { - _, err := NewCommand("tag", name, revision).RunInDir(repo.Path) - return err -} - -func (repo *Repository) getTag(id SHA1) (*Tag, error) { - t, ok := repo.tagCache.Get(id.String()) - if ok { - log("Hit cache: %s", id) - return t.(*Tag), nil - } - - // Get tag type - tp, err := NewCommand("cat-file", "-t", id.String()).RunInDir(repo.Path) - if err != nil { - return nil, err - } - tp = strings.TrimSpace(tp) - - // Tag is a commit. - if ObjectType(tp) == ObjectCommit { - tag := &Tag{ - ID: id, - Object: id, - Type: string(ObjectCommit), - repo: repo, - } - - repo.tagCache.Set(id.String(), tag) - return tag, nil - } - - // Tag with message. - data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - tag, err := parseTagData(data) - if err != nil { - return nil, err - } - - tag.ID = id - tag.repo = repo - - repo.tagCache.Set(id.String(), tag) - return tag, nil -} - -// GetTag returns a Git tag by given name. -func (repo *Repository) GetTag(name string) (*Tag, error) { - stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - id, err := NewIDFromString(strings.Split(stdout, " ")[0]) - if err != nil { - return nil, err - } - - tag, err := repo.getTag(id) - if err != nil { - return nil, err - } - tag.Name = name - return tag, nil -} - -// GetTagInfos returns all tag infos of the repository. -func (repo *Repository) GetTagInfos() ([]*Tag, error) { - // TODO this a slow implementation, makes one git command per tag - stdout, err := NewCommand("tag").RunInDir(repo.Path) - if err != nil { - return nil, err - } - - tagNames := strings.Split(stdout, "\n") - var tags []*Tag - for _, tagName := range tagNames { - tagName = strings.TrimSpace(tagName) - if len(tagName) == 0 { - continue - } - commitID, err := NewCommand("rev-parse", tagName).RunInDir(repo.Path) - if err != nil { - return nil, err - } - commit, err := repo.GetCommit(commitID) - if err != nil { - return nil, err - } - tags = append(tags, &Tag{ - Name: tagName, - Message: commit.Message(), - Object: commit.ID, - Tagger: commit.Author, - }) - } - sortTagsByTime(tags) - return tags, nil -} - -// GetTags returns all tags of the repository. -func (repo *Repository) GetTags() ([]string, error) { - cmd := NewCommand("tag", "-l") - if version.Compare(gitVersion, "2.0.0", ">=") { - cmd.AddArguments("--sort=-v:refname") - } - - stdout, err := cmd.RunInDir(repo.Path) - if err != nil { - return nil, err - } - - tags := strings.Split(stdout, "\n") - tags = tags[:len(tags)-1] - - if version.Compare(gitVersion, "2.0.0", "<") { - version.Sort(tags) - - // Reverse order - for i := 0; i < len(tags)/2; i++ { - j := len(tags) - i - 1 - tags[i], tags[j] = tags[j], tags[i] - } - } - - return tags, nil -} diff --git a/vendor/code.gitea.io/git/repo_tree.go b/vendor/code.gitea.io/git/repo_tree.go deleted file mode 100644 index 6e3843f7e5389..0000000000000 --- a/vendor/code.gitea.io/git/repo_tree.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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 git - -func (repo *Repository) getTree(id SHA1) (*Tree, error) { - treePath := filepathFromSHA1(repo.Path, id.String()) - if isFile(treePath) { - _, err := NewCommand("ls-tree", id.String()).RunInDir(repo.Path) - if err != nil { - return nil, ErrNotExist{id.String(), ""} - } - } - - return NewTree(repo, id), nil -} - -// GetTree find the tree object in the repository. -func (repo *Repository) GetTree(idStr string) (*Tree, error) { - id, err := NewIDFromString(idStr) - if err != nil { - return nil, err - } - return repo.getTree(id) -} diff --git a/vendor/code.gitea.io/git/sha1.go b/vendor/code.gitea.io/git/sha1.go deleted file mode 100644 index 6c9d53949dff9..0000000000000 --- a/vendor/code.gitea.io/git/sha1.go +++ /dev/null @@ -1,76 +0,0 @@ -// 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 git - -import ( - "bytes" - "encoding/hex" - "fmt" - "strings" -) - -// EmptySHA defines empty git SHA -const EmptySHA = "0000000000000000000000000000000000000000" - -// SHA1 a git commit name -type SHA1 [20]byte - -// Equal returns true if s has the same SHA1 as caller. -// Support 40-length-string, []byte, SHA1. -func (id SHA1) Equal(s2 interface{}) bool { - switch v := s2.(type) { - case string: - if len(v) != 40 { - return false - } - return v == id.String() - case []byte: - return bytes.Equal(v, id[:]) - case SHA1: - return v == id - default: - return false - } -} - -// String returns string (hex) representation of the Oid. -func (id SHA1) String() string { - return hex.EncodeToString(id[:]) -} - -// MustID always creates a new SHA1 from a [20]byte array with no validation of input. -func MustID(b []byte) SHA1 { - var id SHA1 - copy(id[:], b) - return id -} - -// NewID creates a new SHA1 from a [20]byte array. -func NewID(b []byte) (SHA1, error) { - if len(b) != 20 { - return SHA1{}, fmt.Errorf("Length must be 20: %v", b) - } - return MustID(b), nil -} - -// MustIDFromString always creates a new sha from a ID with no validation of input. -func MustIDFromString(s string) SHA1 { - b, _ := hex.DecodeString(s) - return MustID(b) -} - -// NewIDFromString creates a new SHA1 from a ID string of length 40. -func NewIDFromString(s string) (SHA1, error) { - var id SHA1 - s = strings.TrimSpace(s) - if len(s) != 40 { - return id, fmt.Errorf("Length must be 40: %s", s) - } - b, err := hex.DecodeString(s) - if err != nil { - return id, err - } - return NewID(b) -} diff --git a/vendor/code.gitea.io/git/signature.go b/vendor/code.gitea.io/git/signature.go deleted file mode 100644 index e6ab247fd73fa..0000000000000 --- a/vendor/code.gitea.io/git/signature.go +++ /dev/null @@ -1,58 +0,0 @@ -// 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 git - -import ( - "bytes" - "strconv" - "time" -) - -// Signature represents the Author or Committer information. -type Signature struct { - Email string - Name string - When time.Time -} - -const ( - // GitTimeLayout is the (default) time layout used by git. - GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700" -) - -// Helper to get a signature from the commit line, which looks like these: -// author Patrick Gundlach 1378823654 +0200 -// author Patrick Gundlach Thu, 07 Apr 2005 22:13:13 +0200 -// but without the "author " at the beginning (this method should) -// be used for author and committer. -// -// FIXME: include timezone for timestamp! -func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { - sig := new(Signature) - emailStart := bytes.IndexByte(line, '<') - sig.Name = string(line[:emailStart-1]) - emailEnd := bytes.IndexByte(line, '>') - sig.Email = string(line[emailStart+1 : emailEnd]) - - // Check date format. - if len(line) > emailEnd+2 { - firstChar := line[emailEnd+2] - if firstChar >= 48 && firstChar <= 57 { - timestop := bytes.IndexByte(line[emailEnd+2:], ' ') - timestring := string(line[emailEnd+2 : emailEnd+2+timestop]) - seconds, _ := strconv.ParseInt(timestring, 10, 64) - sig.When = time.Unix(seconds, 0) - } else { - sig.When, err = time.Parse(GitTimeLayout, string(line[emailEnd+2:])) - if err != nil { - return nil, err - } - } - } else { - // Fall back to unix 0 time - sig.When = time.Unix(0, 0) - } - return sig, nil -} diff --git a/vendor/code.gitea.io/git/submodule.go b/vendor/code.gitea.io/git/submodule.go deleted file mode 100644 index a0fe7b4a5691c..0000000000000 --- a/vendor/code.gitea.io/git/submodule.go +++ /dev/null @@ -1,79 +0,0 @@ -// 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 git - -import "strings" - -// SubModule submodule is a reference on git repository -type SubModule struct { - Name string - URL string -} - -// SubModuleFile represents a file with submodule type. -type SubModuleFile struct { - *Commit - - refURL string - refID string -} - -// NewSubModuleFile create a new submodule file -func NewSubModuleFile(c *Commit, refURL, refID string) *SubModuleFile { - return &SubModuleFile{ - Commit: c, - refURL: refURL, - refID: refID, - } -} - -// RefURL guesses and returns reference URL. -func (sf *SubModuleFile) RefURL(urlPrefix string, parentPath string) string { - if sf.refURL == "" { - return "" - } - - url := strings.TrimSuffix(sf.refURL, ".git") - - // git://xxx/user/repo - if strings.HasPrefix(url, "git://") { - return "http://" + strings.TrimPrefix(url, "git://") - } - - // http[s]://xxx/user/repo - if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { - return url - } - - // Relative url prefix check (according to git submodule documentation) - if strings.HasPrefix(url, "./") || strings.HasPrefix(url, "../") { - // ...construct and return correct submodule url here... - idx := strings.Index(parentPath, "/src/") - if idx == -1 { - return url - } - return strings.TrimSuffix(urlPrefix, "/") + parentPath[:idx] + "/" + url - } - - // sysuser@xxx:user/repo - i := strings.Index(url, "@") - j := strings.LastIndex(url, ":") - - // Only process when i < j because git+ssh://git@git.forwardbias.in/npploader.git - if i > -1 && j > -1 && i < j { - // fix problem with reverse proxy works only with local server - if strings.Contains(urlPrefix, url[i+1:j]) { - return urlPrefix + url[j+1:] - } - return "http://" + url[i+1:j] + "/" + url[j+1:] - } - - return url -} - -// RefID returns reference ID. -func (sf *SubModuleFile) RefID() string { - return sf.refID -} diff --git a/vendor/code.gitea.io/git/tag.go b/vendor/code.gitea.io/git/tag.go deleted file mode 100644 index 500fd274914c4..0000000000000 --- a/vendor/code.gitea.io/git/tag.go +++ /dev/null @@ -1,89 +0,0 @@ -// 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 git - -import ( - "bytes" - "sort" -) - -// Tag represents a Git tag. -type Tag struct { - Name string - ID SHA1 - repo *Repository - Object SHA1 // The id of this commit object - Type string - Tagger *Signature - Message string -} - -// Commit return the commit of the tag reference -func (tag *Tag) Commit() (*Commit, error) { - return tag.repo.getCommit(tag.Object) -} - -// Parse commit information from the (uncompressed) raw -// data from the commit object. -// \n\n separate headers from message -func parseTagData(data []byte) (*Tag, error) { - tag := new(Tag) - // we now have the contents of the commit object. Let's investigate... - nextline := 0 -l: - for { - eol := bytes.IndexByte(data[nextline:], '\n') - switch { - case eol > 0: - line := data[nextline : nextline+eol] - spacepos := bytes.IndexByte(line, ' ') - reftype := line[:spacepos] - switch string(reftype) { - case "object": - id, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - tag.Object = id - case "type": - // A commit can have one or more parents - tag.Type = string(line[spacepos+1:]) - case "tagger": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - tag.Tagger = sig - } - nextline += eol + 1 - case eol == 0: - tag.Message = string(data[nextline+1:]) - break l - default: - break l - } - } - return tag, nil -} - -type tagSorter []*Tag - -func (ts tagSorter) Len() int { - return len([]*Tag(ts)) -} - -func (ts tagSorter) Less(i, j int) bool { - return []*Tag(ts)[i].Tagger.When.After([]*Tag(ts)[j].Tagger.When) -} - -func (ts tagSorter) Swap(i, j int) { - []*Tag(ts)[i], []*Tag(ts)[j] = []*Tag(ts)[j], []*Tag(ts)[i] -} - -// sortTagsByTime -func sortTagsByTime(tags []*Tag) { - sorter := tagSorter(tags) - sort.Sort(sorter) -} diff --git a/vendor/code.gitea.io/git/tree.go b/vendor/code.gitea.io/git/tree.go deleted file mode 100644 index 4654dac30ea7c..0000000000000 --- a/vendor/code.gitea.io/git/tree.go +++ /dev/null @@ -1,72 +0,0 @@ -// 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 git - -import ( - "strings" -) - -// Tree represents a flat directory listing. -type Tree struct { - ID SHA1 - repo *Repository - - // parent tree - ptree *Tree - - entries Entries - entriesParsed bool -} - -// NewTree create a new tree according the repository and commit id -func NewTree(repo *Repository, id SHA1) *Tree { - return &Tree{ - ID: id, - repo: repo, - } -} - -// SubTree get a sub tree by the sub dir path -func (t *Tree) SubTree(rpath string) (*Tree, error) { - if len(rpath) == 0 { - return t, nil - } - - paths := strings.Split(rpath, "/") - var ( - err error - g = t - p = t - te *TreeEntry - ) - for _, name := range paths { - te, err = p.GetTreeEntryByPath(name) - if err != nil { - return nil, err - } - - g, err = t.repo.getTree(te.ID) - if err != nil { - return nil, err - } - g.ptree = p - p = g - } - return g, nil -} - -// ListEntries returns all entries of current tree. -func (t *Tree) ListEntries() (Entries, error) { - if t.entriesParsed { - return t.entries, nil - } - - stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path) - if err != nil { - return nil, err - } - t.entries, err = parseTreeEntries(stdout, t) - return t.entries, err -} diff --git a/vendor/code.gitea.io/git/tree_blob.go b/vendor/code.gitea.io/git/tree_blob.go deleted file mode 100644 index b3d205d8e10e9..0000000000000 --- a/vendor/code.gitea.io/git/tree_blob.go +++ /dev/null @@ -1,59 +0,0 @@ -// 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 git - -import ( - "path" - "strings" -) - -// GetTreeEntryByPath get the tree entries accroding the sub dir -func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { - if len(relpath) == 0 { - return &TreeEntry{ - ID: t.ID, - Type: ObjectTree, - mode: EntryModeTree, - }, nil - } - - relpath = path.Clean(relpath) - parts := strings.Split(relpath, "/") - var err error - tree := t - for i, name := range parts { - if i == len(parts)-1 { - entries, err := tree.ListEntries() - if err != nil { - return nil, err - } - for _, v := range entries { - if v.name == name { - return v, nil - } - } - } else { - tree, err = tree.SubTree(name) - if err != nil { - return nil, err - } - } - } - return nil, ErrNotExist{"", relpath} -} - -// GetBlobByPath get the blob object accroding the path -func (t *Tree) GetBlobByPath(relpath string) (*Blob, error) { - entry, err := t.GetTreeEntryByPath(relpath) - if err != nil { - return nil, err - } - - if !entry.IsDir() { - return entry.Blob(), nil - } - - return nil, ErrNotExist{"", relpath} -} diff --git a/vendor/code.gitea.io/git/tree_entry.go b/vendor/code.gitea.io/git/tree_entry.go deleted file mode 100644 index 6201eef8fd5bd..0000000000000 --- a/vendor/code.gitea.io/git/tree_entry.go +++ /dev/null @@ -1,200 +0,0 @@ -// 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 git - -import ( - "io" - "sort" - "strconv" - "strings" -) - -// EntryMode the type of the object in the git tree -type EntryMode int - -// There are only a few file modes in Git. They look like unix file modes, but they can only be -// one of these. -const ( - // EntryModeBlob - EntryModeBlob EntryMode = 0100644 - // EntryModeExec - EntryModeExec EntryMode = 0100755 - // EntryModeSymlink - EntryModeSymlink EntryMode = 0120000 - // EntryModeCommit - EntryModeCommit EntryMode = 0160000 - // EntryModeTree - EntryModeTree EntryMode = 0040000 -) - -// TreeEntry the leaf in the git tree -type TreeEntry struct { - ID SHA1 - Type ObjectType - - mode EntryMode - name string - - ptree *Tree - - commited bool - - size int64 - sized bool -} - -// Name returns the name of the entry -func (te *TreeEntry) Name() string { - return te.name -} - -// Size returns the size of the entry -func (te *TreeEntry) Size() int64 { - if te.IsDir() { - return 0 - } else if te.sized { - return te.size - } - - stdout, err := NewCommand("cat-file", "-s", te.ID.String()).RunInDir(te.ptree.repo.Path) - if err != nil { - return 0 - } - - te.sized = true - te.size, _ = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) - return te.size -} - -// IsSubModule if the entry is a sub module -func (te *TreeEntry) IsSubModule() bool { - return te.mode == EntryModeCommit -} - -// IsDir if the entry is a sub dir -func (te *TreeEntry) IsDir() bool { - return te.mode == EntryModeTree -} - -// IsLink if the entry is a symlink -func (te *TreeEntry) IsLink() bool { - return te.mode == EntryModeSymlink -} - -// Blob retrun the blob object the entry -func (te *TreeEntry) Blob() *Blob { - return &Blob{ - repo: te.ptree.repo, - TreeEntry: te, - } -} - -// FollowLink returns the entry pointed to by a symlink -func (te *TreeEntry) FollowLink() (*TreeEntry, error) { - if !te.IsLink() { - return nil, ErrBadLink{te.Name(), "not a symlink"} - } - - // read the link - r, err := te.Blob().Data() - if err != nil { - return nil, err - } - buf := make([]byte, te.Size()) - _, err = io.ReadFull(r, buf) - if err != nil { - return nil, err - } - - lnk := string(buf) - t := te.ptree - - // traverse up directories - for ; t != nil && strings.HasPrefix(lnk, "../"); lnk = lnk[3:] { - t = t.ptree - } - - if t == nil { - return nil, ErrBadLink{te.Name(), "points outside of repo"} - } - - target, err := t.GetTreeEntryByPath(lnk) - if err != nil { - if IsErrNotExist(err) { - return nil, ErrBadLink{te.Name(), "broken link"} - } - return nil, err - } - return target, nil -} - -// GetSubJumpablePathName return the full path of subdirectory jumpable ( contains only one directory ) -func (te *TreeEntry) GetSubJumpablePathName() string { - if te.IsSubModule() || !te.IsDir() { - return "" - } - tree, err := te.ptree.SubTree(te.name) - if err != nil { - return te.name - } - entries, _ := tree.ListEntries() - if len(entries) == 1 && entries[0].IsDir() { - name := entries[0].GetSubJumpablePathName() - if name != "" { - return te.name + "/" + name - } - } - return te.name -} - -// Entries a list of entry -type Entries []*TreeEntry - -type customSortableEntries struct { - Comparer func(s1, s2 string) bool - Entries -} - -var sorter = []func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool{ - func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { - return (t1.IsDir() || t1.IsSubModule()) && !t2.IsDir() && !t2.IsSubModule() - }, - func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { - return cmp(t1.name, t2.name) - }, -} - -func (ctes customSortableEntries) Len() int { return len(ctes.Entries) } - -func (ctes customSortableEntries) Swap(i, j int) { - ctes.Entries[i], ctes.Entries[j] = ctes.Entries[j], ctes.Entries[i] -} - -func (ctes customSortableEntries) Less(i, j int) bool { - t1, t2 := ctes.Entries[i], ctes.Entries[j] - var k int - for k = 0; k < len(sorter)-1; k++ { - s := sorter[k] - switch { - case s(t1, t2, ctes.Comparer): - return true - case s(t2, t1, ctes.Comparer): - return false - } - } - return sorter[k](t1, t2, ctes.Comparer) -} - -// Sort sort the list of entry -func (tes Entries) Sort() { - sort.Sort(customSortableEntries{func(s1, s2 string) bool { - return s1 < s2 - }, tes}) -} - -// CustomSort customizable string comparing sort entry list -func (tes Entries) CustomSort(cmp func(s1, s2 string) bool) { - sort.Sort(customSortableEntries{cmp, tes}) -} diff --git a/vendor/code.gitea.io/git/utils.go b/vendor/code.gitea.io/git/utils.go deleted file mode 100644 index 8f010321cf836..0000000000000 --- a/vendor/code.gitea.io/git/utils.go +++ /dev/null @@ -1,96 +0,0 @@ -// 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 git - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "sync" -) - -// ObjectCache provides thread-safe cache opeations. -type ObjectCache struct { - lock sync.RWMutex - cache map[string]interface{} -} - -func newObjectCache() *ObjectCache { - return &ObjectCache{ - cache: make(map[string]interface{}, 10), - } -} - -// Set add obj to cache -func (oc *ObjectCache) Set(id string, obj interface{}) { - oc.lock.Lock() - defer oc.lock.Unlock() - - oc.cache[id] = obj -} - -// Get get cached obj by id -func (oc *ObjectCache) Get(id string) (interface{}, bool) { - oc.lock.RLock() - defer oc.lock.RUnlock() - - obj, has := oc.cache[id] - return obj, has -} - -// isDir returns true if given path is a directory, -// or returns false when it's a file or does not exist. -func isDir(dir string) bool { - f, e := os.Stat(dir) - if e != nil { - return false - } - return f.IsDir() -} - -// isFile returns true if given path is a file, -// or returns false when it's a directory or does not exist. -func isFile(filePath string) bool { - f, e := os.Stat(filePath) - if e != nil { - return false - } - return !f.IsDir() -} - -// isExist checks whether a file or directory exists. -// It returns false when the file or directory does not exist. -func isExist(path string) bool { - _, err := os.Stat(path) - return err == nil || os.IsExist(err) -} - -func concatenateError(err error, stderr string) error { - if len(stderr) == 0 { - return err - } - return fmt.Errorf("%v - %s", err, stderr) -} - -// If the object is stored in its own file (i.e not in a pack file), -// this function returns the full path to the object file. -// It does not test if the file exists. -func filepathFromSHA1(rootdir, sha1 string) string { - return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:]) -} - -// RefEndName return the end name of a ref name -func RefEndName(refStr string) string { - if strings.HasPrefix(refStr, BranchPrefix) { - return refStr[len(BranchPrefix):] - } - - if strings.HasPrefix(refStr, TagPrefix) { - return refStr[len(TagPrefix):] - } - - return refStr -} diff --git a/vendor/code.gitea.io/sdk/LICENSE b/vendor/code.gitea.io/sdk/LICENSE deleted file mode 100644 index 10aeba46bcfc9..0000000000000 --- a/vendor/code.gitea.io/sdk/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 4071b6f187fcc..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/admin_org.go +++ /dev/null @@ -1,22 +0,0 @@ -// 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" -) - -// 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 deleted file mode 100644 index cf565ffa38b1c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/admin_repo.go +++ /dev/null @@ -1,22 +0,0 @@ -// 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 deleted file mode 100644 index 4eab8c255fdbd..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/admin_user.go +++ /dev/null @@ -1,82 +0,0 @@ -// 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" -) - -// CreateUserOption create user options -type CreateUserOption struct { - SourceID int64 `json:"source_id"` - LoginName string `json:"login_name"` - // required: true - Username string `json:"username" binding:"Required;AlphaDashDot;MaxSize(35)"` - FullName string `json:"full_name" binding:"MaxSize(100)"` - // required: true - // swagger:strfmt email - Email string `json:"email" binding:"Required;Email;MaxSize(254)"` - // required: true - Password string `json:"password" binding:"Required;MaxSize(255)"` - 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" binding:"MaxSize(100)"` - // required: true - // swagger:strfmt email - Email string `json:"email" binding:"Required;Email;MaxSize(254)"` - Password string `json:"password" binding:"MaxSize(255)"` - Website string `json:"website" binding:"MaxSize(50)"` - Location string `json:"location" binding:"MaxSize(50)"` - 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 create one user with options -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) -} diff --git a/vendor/code.gitea.io/sdk/gitea/attachment.go b/vendor/code.gitea.io/sdk/gitea/attachment.go deleted file mode 100644 index 8c527de735c39..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/attachment.go +++ /dev/null @@ -1,92 +0,0 @@ -// 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 -// swagger:model -type Attachment struct { - ID int64 `json:"id"` - Name string `json:"name"` - Size int64 `json:"size"` - DownloadCount int64 `json:"download_count"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - UUID string `json:"uuid"` - DownloadURL string `json:"browser_download_url"` -} - -// ListReleaseAttachments list release's attachments -func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*Attachment, error) { - attachments := make([]*Attachment, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), - 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 -} - -// 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 -} - -// EditAttachmentOptions options for editing attachments -// swagger:model -type EditAttachmentOptions struct { - Name string `json:"name"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/doc.go b/vendor/code.gitea.io/sdk/gitea/doc.go deleted file mode 100644 index 6bd327db4623c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// 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 deleted file mode 100644 index 57222498ef54c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/fork.go +++ /dev/null @@ -1,39 +0,0 @@ -// 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" -) - -// ListForks list a repository's forks -func (c *Client) ListForks(user, repo string) ([]*Repository, error) { - forks := make([]*Repository, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/forks", user, repo), - nil, nil, &forks) - return forks, err -} - -// 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) - err = c.getParsedResponse("POST", - fmt.Sprintf("/repos/%s/%s/forks", user, repo), - jsonHeader, bytes.NewReader(body), &fork) - return fork, err -} diff --git a/vendor/code.gitea.io/sdk/gitea/gitea.go b/vendor/code.gitea.io/sdk/gitea/gitea.go deleted file mode 100644 index 374a3faa9604c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/gitea.go +++ /dev/null @@ -1,104 +0,0 @@ -// 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 ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Version return the library version -func Version() string { - return "0.12.3" -} - -// Client represents a Gogs API client. -type Client struct { - url string - accessToken string - client *http.Client -} - -// NewClient initializes and returns a API client. -func NewClient(url, token string) *Client { - return &Client{ - url: strings.TrimSuffix(url, "/"), - accessToken: token, - client: &http.Client{}, - } -} - -// SetHTTPClient replaces default http.Client with user given one. -func (c *Client) SetHTTPClient(client *http.Client) { - c.client = client -} - -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 - } - req.Header.Set("Authorization", "token "+c.accessToken) - 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 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 { - return nil, err - } - 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/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go deleted file mode 100644 index f346381679848..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/hook.go +++ /dev/null @@ -1,531 +0,0 @@ -// 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" - "errors" - "fmt" - "strings" - "time" -) - -var ( - // ErrInvalidReceiveHook FIXME - ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") -) - -// 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"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` -} - -// HookList represents a list of API hook. -type HookList []*Hook - -// ListOrgHooks list all the hooks of one organization -func (c *Client) ListOrgHooks(org string) (HookList, error) { - hooks := make([]*Hook, 0, 10) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks", org), nil, nil, &hooks) -} - -// ListRepoHooks list all the hooks of one repository -func (c *Client) ListRepoHooks(user, repo string) (HookList, error) { - hooks := make([]*Hook, 0, 10) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), 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 { - // required: true - // enum: gitea,gogs,slack,discord - Type string `json:"type" binding:"Required"` - // required: true - Config map[string]string `json:"config" binding:"Required"` - Events []string `json:"events"` - // default: false - 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"` - 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("/org/%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 -} - -// Payloader payload is some part of one hook -type Payloader interface { - SetSecret(string) - JSONPayload() ([]byte, error) -} - -// PayloadUser represents the author or committer of a commit -type PayloadUser struct { - // Full name of the commit author - Name string `json:"name"` - // swagger:strfmt email - 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"` - // swagger:strfmt date-time - Timestamp time.Time `json:"timestamp"` -} - -// 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"` -} - -var ( - _ Payloader = &CreatePayload{} - _ Payloader = &DeletePayload{} - _ Payloader = &ForkPayload{} - _ Payloader = &PushPayload{} - _ Payloader = &IssuePayload{} - _ Payloader = &IssueCommentPayload{} - _ Payloader = &PullRequestPayload{} - _ Payloader = &RepositoryPayload{} - _ Payloader = &ReleasePayload{} -) - -// _________ __ -// \_ ___ \_______ ____ _____ _/ |_ ____ -// / \ \/\_ __ \_/ __ \\__ \\ __\/ __ \ -// \ \____| | \/\ ___/ / __ \| | \ ___/ -// \______ /|__| \___ >____ /__| \___ > -// \/ \/ \/ \/ - -// CreatePayload FIXME -type CreatePayload struct { - Secret string `json:"secret"` - Sha string `json:"sha"` - Ref string `json:"ref"` - RefType string `json:"ref_type"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret FIXME -func (p *CreatePayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload return payload information -func (p *CreatePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ParseCreateHook parses create event hook content. -func ParseCreateHook(raw []byte) (*CreatePayload, error) { - hook := new(CreatePayload) - if err := json.Unmarshal(raw, hook); err != nil { - return nil, err - } - - // it is possible the JSON was parsed, however, - // was not from Gogs (maybe was from Bitbucket) - // So we'll check to be sure certain key fields - // were populated - switch { - case hook.Repo == nil: - return nil, ErrInvalidReceiveHook - case len(hook.Ref) == 0: - return nil, ErrInvalidReceiveHook - } - return hook, nil -} - -// ________ .__ __ -// \______ \ ____ | | _____/ |_ ____ -// | | \_/ __ \| | _/ __ \ __\/ __ \ -// | ` \ ___/| |_\ ___/| | \ ___/ -// /_______ /\___ >____/\___ >__| \___ > -// \/ \/ \/ \/ - -// PusherType define the type to push -type PusherType string - -// describe all the PusherTypes -const ( - PusherTypeUser PusherType = "user" -) - -// DeletePayload represents delete payload -type DeletePayload struct { - Ref string `json:"ref"` - RefType string `json:"ref_type"` - PusherType PusherType `json:"pusher_type"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *DeletePayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *DeletePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ___________ __ -// \_ _____/__________| | __ -// | __)/ _ \_ __ \ |/ / -// | \( <_> ) | \/ < -// \___ / \____/|__| |__|_ \ -// \/ \/ - -// ForkPayload represents fork payload -type ForkPayload struct { - Forkee *Repository `json:"forkee"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *ForkPayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *ForkPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// HookIssueCommentAction defines hook issue comment action -type HookIssueCommentAction string - -// all issue comment actions -const ( - HookIssueCommentCreated HookIssueCommentAction = "created" - HookIssueCommentEdited HookIssueCommentAction = "edited" - HookIssueCommentDeleted HookIssueCommentAction = "deleted" -) - -// IssueCommentPayload represents a payload information of issue comment event. -type IssueCommentPayload struct { - Action HookIssueCommentAction `json:"action"` - Issue *Issue `json:"issue"` - Comment *Comment `json:"comment"` - Changes *ChangesPayload `json:"changes,omitempty"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *IssueCommentPayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *IssueCommentPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// __________ .__ -// \______ \ ____ | | ____ _____ ______ ____ -// | _// __ \| | _/ __ \\__ \ / ___// __ \ -// | | \ ___/| |_\ ___/ / __ \_\___ \\ ___/ -// |____|_ /\___ >____/\___ >____ /____ >\___ > -// \/ \/ \/ \/ \/ \/ - -// HookReleaseAction defines hook release action type -type HookReleaseAction string - -// all release actions -const ( - HookReleasePublished HookReleaseAction = "published" - HookReleaseUpdated HookReleaseAction = "updated" - HookReleaseDeleted HookReleaseAction = "deleted" -) - -// ReleasePayload represents a payload information of release event. -type ReleasePayload struct { - Action HookReleaseAction `json:"action"` - Release *Release `json:"release"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *ReleasePayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *ReleasePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// __________ .__ -// \______ \__ __ _____| |__ -// | ___/ | \/ ___/ | \ -// | | | | /\___ \| Y \ -// |____| |____//____ >___| / -// \/ \/ - -// PushPayload represents a payload information of push event. -type PushPayload struct { - Secret string `json:"secret"` - Ref string `json:"ref"` - Before string `json:"before"` - After string `json:"after"` - CompareURL string `json:"compare_url"` - Commits []*PayloadCommit `json:"commits"` - Repo *Repository `json:"repository"` - Pusher *User `json:"pusher"` - Sender *User `json:"sender"` -} - -// SetSecret FIXME -func (p *PushPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload FIXME -func (p *PushPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ParsePushHook parses push event hook content. -func ParsePushHook(raw []byte) (*PushPayload, error) { - hook := new(PushPayload) - if err := json.Unmarshal(raw, hook); err != nil { - return nil, err - } - - switch { - case hook.Repo == nil: - return nil, ErrInvalidReceiveHook - case len(hook.Ref) == 0: - return nil, ErrInvalidReceiveHook - } - return hook, nil -} - -// Branch returns branch name from a payload -func (p *PushPayload) Branch() string { - return strings.Replace(p.Ref, "refs/heads/", "", -1) -} - -// .___ -// | | ______ ________ __ ____ -// | |/ ___// ___/ | \_/ __ \ -// | |\___ \ \___ \| | /\ ___/ -// |___/____ >____ >____/ \___ > -// \/ \/ \/ - -// HookIssueAction FIXME -type HookIssueAction string - -const ( - // HookIssueOpened opened - HookIssueOpened HookIssueAction = "opened" - // HookIssueClosed closed - HookIssueClosed HookIssueAction = "closed" - // HookIssueReOpened reopened - HookIssueReOpened HookIssueAction = "reopened" - // HookIssueEdited edited - HookIssueEdited HookIssueAction = "edited" - // HookIssueAssigned assigned - HookIssueAssigned HookIssueAction = "assigned" - // HookIssueUnassigned unassigned - HookIssueUnassigned HookIssueAction = "unassigned" - // HookIssueLabelUpdated label_updated - HookIssueLabelUpdated HookIssueAction = "label_updated" - // HookIssueLabelCleared label_cleared - HookIssueLabelCleared HookIssueAction = "label_cleared" - // HookIssueSynchronized synchronized - HookIssueSynchronized HookIssueAction = "synchronized" - // HookIssueMilestoned is an issue action for when a milestone is set on an issue. - HookIssueMilestoned HookIssueAction = "milestoned" - // HookIssueDemilestoned is an issue action for when a milestone is cleared on an issue. - HookIssueDemilestoned HookIssueAction = "demilestoned" -) - -// IssuePayload represents the payload information that is sent along with an issue event. -type IssuePayload struct { - Secret string `json:"secret"` - Action HookIssueAction `json:"action"` - Index int64 `json:"number"` - Changes *ChangesPayload `json:"changes,omitempty"` - Issue *Issue `json:"issue"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret modifies the secret of the IssuePayload. -func (p *IssuePayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload encodes the IssuePayload to JSON, with an indentation of two spaces. -func (p *IssuePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ChangesFromPayload FIXME -type ChangesFromPayload struct { - From string `json:"from"` -} - -// ChangesPayload FIXME -type ChangesPayload struct { - Title *ChangesFromPayload `json:"title,omitempty"` - Body *ChangesFromPayload `json:"body,omitempty"` -} - -// __________ .__ .__ __________ __ -// \______ \__ __| | | | \______ \ ____ ________ __ ____ _______/ |_ -// | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\ -// | | | | / |_| |__ | | \ ___< <_| | | /\ ___/ \___ \ | | -// |____| |____/|____/____/ |____|_ /\___ >__ |____/ \___ >____ > |__| -// \/ \/ |__| \/ \/ - -// PullRequestPayload represents a payload information of pull request event. -type PullRequestPayload struct { - Secret string `json:"secret"` - Action HookIssueAction `json:"action"` - Index int64 `json:"number"` - Changes *ChangesPayload `json:"changes,omitempty"` - PullRequest *PullRequest `json:"pull_request"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret modifies the secret of the PullRequestPayload. -func (p *PullRequestPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload FIXME -func (p *PullRequestPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -//__________ .__ __ -//\______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. -// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | -// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ | -// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| -// \/ \/|__| \/ \/ - -// HookRepoAction an action that happens to a repo -type HookRepoAction string - -const ( - // HookRepoCreated created - HookRepoCreated HookRepoAction = "created" - // HookRepoDeleted deleted - HookRepoDeleted HookRepoAction = "deleted" -) - -// RepositoryPayload payload for repository webhooks -type RepositoryPayload struct { - Secret string `json:"secret"` - Action HookRepoAction `json:"action"` - Repository *Repository `json:"repository"` - Organization *User `json:"organization"` - Sender *User `json:"sender"` -} - -// SetSecret set the payload's secret -func (p *RepositoryPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload JSON representation of the payload -func (p *RepositoryPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} diff --git a/vendor/code.gitea.io/sdk/gitea/issue.go b/vendor/code.gitea.io/sdk/gitea/issue.go deleted file mode 100644 index fee7cd6f9fca2..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue.go +++ /dev/null @@ -1,154 +0,0 @@ -// 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" - "time" -) - -// StateType issue state type -type StateType string - -const ( - // StateOpen pr is opend - StateOpen StateType = "open" - // StateClosed pr is closed - StateClosed StateType = "closed" -) - -// PullRequestMeta PR info if an issue is a PR -type PullRequestMeta struct { - HasMerged bool `json:"merged"` - Merged *time.Time `json:"merged_at"` -} - -// Issue represents an issue in a repository -// swagger:model -type Issue 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"` - // Whether the issue is open or closed - // - // type: string - // enum: open,closed - State StateType `json:"state"` - Comments int `json:"comments"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` - // swagger:strfmt date-time - Closed *time.Time `json:"closed_at"` - // swagger:strfmt date-time - Deadline *time.Time `json:"due_date"` - - PullRequest *PullRequestMeta `json:"pull_request"` -} - -// ListIssueOption list issue options -type ListIssueOption struct { - Page int - State string -} - -// ListIssues returns all issues assigned the authenticated user -func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { - issues := make([]*Issue, 0, 10) - return issues, c.getParsedResponse("GET", fmt.Sprintf("/issues?page=%d", opt.Page), nil, nil, &issues) -} - -// ListUserIssues returns all issues assigned to the authenticated user -func (c *Client) ListUserIssues(opt ListIssueOption) ([]*Issue, error) { - issues := make([]*Issue, 0, 10) - return issues, c.getParsedResponse("GET", fmt.Sprintf("/user/issues?page=%d", opt.Page), nil, nil, &issues) -} - -// ListRepoIssues returns all issues for a given repository -func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) { - issues := make([]*Issue, 0, 10) - return issues, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues?page=%d", owner, repo, opt.Page), nil, nil, &issues) -} - -// GetIssue returns a single issue for a given repository -func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { - issue := new(Issue) - return issue, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) -} - -// CreateIssueOption options to create one issue -type CreateIssueOption struct { - // required:true - Title string `json:"title" binding:"Required"` - Body string `json:"body"` - // username of assignee - Assignee string `json:"assignee"` - Assignees []string `json:"assignees"` - // swagger:strfmt date-time - 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 *string `json:"state"` - // swagger:strfmt date-time - 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) -} - -// EditDeadlineOption options for creating a deadline -type EditDeadlineOption struct { - // required:true - // swagger:strfmt date-time - Deadline *time.Time `json:"due_date"` -} - -// IssueDeadline represents an issue deadline -// swagger:model -type IssueDeadline struct { - // swagger:strfmt date-time - Deadline *time.Time `json:"due_date"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_comment.go b/vendor/code.gitea.io/sdk/gitea/issue_comment.go deleted file mode 100644 index 2c8127c609734..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_comment.go +++ /dev/null @@ -1,76 +0,0 @@ -// 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" - "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"` - Body string `json:"body"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` -} - -// ListIssueComments list comments on an issue. -func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, error) { - comments := make([]*Comment, 0, 10) - return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments) -} - -// ListRepoIssueComments list comments for a given repo. -func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) { - comments := make([]*Comment, 0, 10) - return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments) -} - -// CreateIssueCommentOption options for creating a comment on an issue -type CreateIssueCommentOption struct { - // required:true - Body string `json:"body" binding:"Required"` -} - -// 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 { - // required: true - Body string `json:"body" binding:"Required"` -} - -// EditIssueComment edits an issue comment. -func (c *Client) EditIssueComment(owner, repo string, index, 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/%d/comments/%d", owner, repo, index, commentID), jsonHeader, bytes.NewReader(body), comment) -} - -// DeleteIssueComment deletes an issue comment. -func (c *Client) DeleteIssueComment(owner, repo string, index, commentID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, 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 deleted file mode 100644 index 47d1b8221e98b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_label.go +++ /dev/null @@ -1,122 +0,0 @@ -// 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 -// swagger:model -type Label struct { - ID int64 `json:"id"` - Name string `json:"name"` - // example: 00aabb - Color string `json:"color"` - URL string `json:"url"` -} - -// ListRepoLabels list labels of one repository -func (c *Client) ListRepoLabels(owner, repo string) ([]*Label, error) { - labels := make([]*Label, 0, 10) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), nil, nil, &labels) -} - -// 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 { - // required:true - Name string `json:"name" binding:"Required"` - // required:true - // example: #00aabb - Color string `json:"color" binding:"Required;Size(7)"` -} - -// CreateLabel create one label of repository -func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { - 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"` -} - -// 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 -} - -// IssueLabelsOption a collection of labels -type IssueLabelsOption struct { - // list of label IDs - Labels []int64 `json:"labels"` -} - -// GetIssueLabels get labels of one issue via issue id -func (c *Client) GetIssueLabels(owner, repo string, index int64) ([]*Label, error) { - labels := make([]*Label, 0, 5) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil, &labels) -} - -// 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 deleted file mode 100644 index 775a6a9117510..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ /dev/null @@ -1,80 +0,0 @@ -// 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" - "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"` - // swagger:strfmt date-time - Closed *time.Time `json:"closed_at"` - // swagger:strfmt date-time - Deadline *time.Time `json:"due_on"` -} - -// ListRepoMilestones list all the milestones of one repository -func (c *Client) ListRepoMilestones(owner, repo string) ([]*Milestone, error) { - milestones := make([]*Milestone, 0, 10) - return milestones, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), nil, nil, &milestones) -} - -// 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"` - // swagger:strfmt date-time - 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) - return milestone, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) -} - -// 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_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go deleted file mode 100644 index 7f4b64cbb3f99..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go +++ /dev/null @@ -1,68 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created"` - // Time in seconds - Time int64 `json:"time"` - UserID int64 `json:"user_id"` - IssueID int64 `json:"issue_id"` -} - -// TrackedTimes represent a list of tracked times -type TrackedTimes []*TrackedTime - -// GetUserTrackedTimes list tracked times of a user -func (c *Client) GetUserTrackedTimes(owner, repo, user string) (TrackedTimes, error) { - times := make(TrackedTimes, 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) (TrackedTimes, error) { - times := make(TrackedTimes, 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() (TrackedTimes, error) { - times := make(TrackedTimes, 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 - // required: true - Time int64 `json:"time" binding:"Required"` -} - -// 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) -} - -// ListTrackedTimes get tracked times of one issue via issue id -func (c *Client) ListTrackedTimes(owner, repo string, index int64) (TrackedTimes, error) { - times := make(TrackedTimes, 0, 5) - return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil, ×) -} diff --git a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go deleted file mode 100644 index 356636a3a2519..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go +++ /dev/null @@ -1,65 +0,0 @@ -// 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 ( - "time" -) - -// LFSLock represent a lock -// for use with the locks API. -type LFSLock struct { - ID string `json:"id"` - Path string `json:"path"` - LockedAt time.Time `json:"locked_at"` - Owner *LFSLockOwner `json:"owner"` -} - -// LFSLockOwner represent a lock owner -// for use with the locks API. -type LFSLockOwner struct { - Name string `json:"name"` -} - -// LFSLockRequest contains the path of the lock to create -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock -type LFSLockRequest struct { - Path string `json:"path"` -} - -// LFSLockResponse represent a lock created -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock -type LFSLockResponse struct { - Lock *LFSLock `json:"lock"` -} - -// LFSLockList represent a list of lock requested -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks -type LFSLockList struct { - Locks []*LFSLock `json:"locks"` - Next string `json:"next_cursor,omitempty"` -} - -// LFSLockListVerify represent a list of lock verification requested -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks-for-verification -type LFSLockListVerify struct { - Ours []*LFSLock `json:"ours"` - Theirs []*LFSLock `json:"theirs"` - Next string `json:"next_cursor,omitempty"` -} - -// LFSLockError contains information on the error that occurs -type LFSLockError struct { - Message string `json:"message"` - Lock *LFSLock `json:"lock,omitempty"` - Documentation string `json:"documentation_url,omitempty"` - RequestID string `json:"request_id,omitempty"` -} - -// LFSLockDeleteRequest contains params of a delete request -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#delete-lock -type LFSLockDeleteRequest struct { - Force bool `json:"force"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go deleted file mode 100644 index 3735047b7f886..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go +++ /dev/null @@ -1,52 +0,0 @@ -// 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 - -// SearchResults results of a successful search -type SearchResults struct { - OK bool `json:"ok"` - Data []*Repository `json:"data"` -} - -// SearchError error of a failed search -type SearchError struct { - OK bool `json:"ok"` - Error string `json:"error"` -} - -// MarkdownOption markdown options -type MarkdownOption struct { - // Text markdown to render - // - // in: body - Text string - // Mode to render - // - // in: body - Mode string - // Context to render - // - // in: body - Context string - // Is it a wiki page ? - // - // in: body - Wiki bool -} - -// MarkdownRender is a rendered markdown document -// swagger:response MarkdownRender -type MarkdownRender string - -// ServerVersion wraps the version of the server -type ServerVersion struct { - Version string `json:"version"` -} - -// ServerVersion returns the version of the server -func (c *Client) ServerVersion() (string, error) { - v := ServerVersion{} - return v.Version, c.getParsedResponse("GET", "/api/v1/version", nil, nil, &v) -} diff --git a/vendor/code.gitea.io/sdk/gitea/org.go b/vendor/code.gitea.io/sdk/gitea/org.go deleted file mode 100644 index 19238d1028453..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org.go +++ /dev/null @@ -1,68 +0,0 @@ -// 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" -) - -// 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"` -} - -// ListMyOrgs list all of current user's organizations -func (c *Client) ListMyOrgs() ([]*Organization, error) { - orgs := make([]*Organization, 0, 5) - return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs) -} - -// ListUserOrgs list all of some user's organizations -func (c *Client) ListUserOrgs(user string) ([]*Organization, error) { - orgs := make([]*Organization, 0, 5) - return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs) -} - -// 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 { - // required: true - UserName string `json:"username" binding:"Required"` - FullName string `json:"full_name"` - Description string `json:"description"` - Website string `json:"website"` - Location string `json:"location"` -} - -// 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"` -} - -// 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 -} diff --git a/vendor/code.gitea.io/sdk/gitea/org_member.go b/vendor/code.gitea.io/sdk/gitea/org_member.go deleted file mode 100644 index 9bb95af3e2624..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org_member.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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" -) - -// AddOrgMembershipOption add user to organization options -type AddOrgMembershipOption struct { - Role string `json:"role" binding:"Required"` -} - -// AddOrgMembership add some one to an organization's member -func (c *Client) AddOrgMembership(org, user string, opt AddOrgMembershipOption) error { - body, err := json.Marshal(&opt) - if err != nil { - return err - } - _, err = c.getResponse("PUT", fmt.Sprintf("/orgs/%s/membership/%s", org, user), jsonHeader, bytes.NewReader(body)) - return err -} diff --git a/vendor/code.gitea.io/sdk/gitea/org_team.go b/vendor/code.gitea.io/sdk/gitea/org_team.go deleted file mode 100644 index 2fc6796d43ff9..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org_team.go +++ /dev/null @@ -1,32 +0,0 @@ -// 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 - -// Team represents a team in an organization -type Team struct { - ID int64 `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - // enum: none,read,write,admin,owner - Permission string `json:"permission"` -} - -// CreateTeamOption options for creating a team -type CreateTeamOption struct { - // required: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` - Description string `json:"description" binding:"MaxSize(255)"` - // enum: read,write,admin - Permission string `json:"permission"` -} - -// EditTeamOption options for editing a team -type EditTeamOption struct { - // required: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` - Description string `json:"description" binding:"MaxSize(255)"` - // enum: read,write,admin - Permission string `json:"permission"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go deleted file mode 100644 index 6fcdd1d41b7e4..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/pull.go +++ /dev/null @@ -1,151 +0,0 @@ -// 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" - "time" -) - -// 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"` - // swagger:strfmt date-time - 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"` - - // swagger:strfmt date-time - Deadline *time.Time `json:"due_date"` - - // swagger:strfmt date-time - Created *time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated *time.Time `json:"updated_at"` - // swagger:strfmt date-time - Closed *time.Time `json:"closed_at"` -} - -// 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"` -} - -// ListPullRequestsOptions options for listing pull requests -type ListPullRequestsOptions struct { - Page int `json:"page"` - State string `json:"state"` -} - -// ListRepoPullRequests list PRs of one repository -func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { - body, err := json.Marshal(&opt) - if err != nil { - return nil, err - } - prs := make([]*PullRequest, 0, 10) - return prs, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), jsonHeader, bytes.NewReader(body), &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" binding:"Required"` - Base string `json:"base" binding:"Required"` - Title string `json:"title" binding:"Required"` - Body string `json:"body"` - Assignee string `json:"assignee"` - Assignees []string `json:"assignees"` - Milestone int64 `json:"milestone"` - Labels []int64 `json:"labels"` - // swagger:strfmt date-time - 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"` - Assignee string `json:"assignee"` - Assignees []string `json:"assignees"` - Milestone int64 `json:"milestone"` - Labels []int64 `json:"labels"` - State *string `json:"state"` - // swagger:strfmt date-time - 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/issues/%d", owner, repo, index), - jsonHeader, bytes.NewReader(body), pr) -} - -// MergePullRequest merge a PR to repository by PR id -func (c *Client) MergePullRequest(owner, repo string, index int64) error { - _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) - return err -} - -// 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/release.go b/vendor/code.gitea.io/sdk/gitea/release.go deleted file mode 100644 index 396251dcac9d8..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/release.go +++ /dev/null @@ -1,105 +0,0 @@ -// 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"` - // swagger:strfmt date-time - CreatedAt time.Time `json:"created_at"` - // swagger:strfmt date-time - PublishedAt time.Time `json:"published_at"` - Publisher *User `json:"author"` - Attachments []*Attachment `json:"assets"` -} - -// ListReleases list releases of a repository -func (c *Client) ListReleases(user, repo string) ([]*Release, error) { - releases := make([]*Release, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/releases", user, repo), - 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 { - // required: true - TagName string `json:"tag_name" binding:"Required"` - 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 deleted file mode 100644 index 339cbd33deaac..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo.go +++ /dev/null @@ -1,155 +0,0 @@ -// 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" - "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"` - 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` - Permissions *Permission `json:"permissions,omitempty"` -} - -// ListMyRepos lists all repositories for the authenticated user that has access to. -func (c *Client) ListMyRepos() ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos) -} - -// ListUserRepos list all repositories of one user by user's name -func (c *Client) ListUserRepos(user string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos", user), nil, nil, &repos) -} - -// ListOrgRepos list all repositories of one organization by organization's name -func (c *Client) ListOrgRepos(org string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos", org), nil, nil, &repos) -} - -// CreateRepoOption options when creating repository -// swagger:model -type CreateRepoOption struct { - // Name of the repository to create - // - // required: true - // unique: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(100)"` - // Description of the repository to create - Description string `json:"description" binding:"MaxSize(255)"` - // Whether the repository is private - Private bool `json:"private"` - // 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"` -} - -// 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) -} - -// 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 { - // required: true - CloneAddr string `json:"clone_addr" binding:"Required"` - AuthUsername string `json:"auth_username"` - AuthPassword string `json:"auth_password"` - // required: true - UID int `json:"uid" binding:"Required"` - // required: true - RepoName string `json:"repo_name" binding:"Required"` - 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 deleted file mode 100644 index 481fc3386ee76..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch.go +++ /dev/null @@ -1,27 +0,0 @@ -// 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 ( - "fmt" -) - -// Branch represents a repository branch -type Branch struct { - Name string `json:"name"` - Commit *PayloadCommit `json:"commit"` -} - -// ListRepoBranches list all the branches of one repository -func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) { - branches := make([]*Branch, 0, 10) - return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches) -} - -// GetRepoBranch get one branch's information of one repository -func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { - b := new(Branch) - return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b) -} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go deleted file mode 100644 index bd61a22cec4f5..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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" -) - -// ListCollaborators list a repository's collaborators -func (c *Client) ListCollaborators(user, repo string) ([]*User, error) { - collaborators := make([]*User, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/collaborators", user, repo), - nil, nil, &collaborators) - return collaborators, err -} - -// IsCollaborator check if a user is a collaborator of a repository -func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { - status, err := c.getStatusCode("GET", - fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), - nil, nil) - 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), nil, 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_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go deleted file mode 100644 index e6c89f0c0f28b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_file.go +++ /dev/null @@ -1,15 +0,0 @@ -// 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" -) - -// 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) -} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_key.go b/vendor/code.gitea.io/sdk/gitea/repo_key.go deleted file mode 100644 index ec53311bdaa55..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_key.go +++ /dev/null @@ -1,69 +0,0 @@ -// 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" -) - -// DeployKey a deploy key -type DeployKey struct { - ID int64 `json:"id"` - Key string `json:"key"` - URL string `json:"url"` - Title string `json:"title"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - ReadOnly bool `json:"read_only"` -} - -// ListDeployKeys list all the deploy keys of one repository -func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) { - keys := make([]*DeployKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys) -} - -// 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) -} - -// CreateKeyOption options when creating a key -type CreateKeyOption struct { - // Title of the key to add - // - // required: true - // unique: true - Title string `json:"title" binding:"Required"` - // An armored SSH key to add - // - // required: true - // unique: true - Key string `json:"key" binding:"Required"` - // Describe if the key has only read access or read/write - // - // required: false - ReadOnly bool `json:"read_only"` -} - -// 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_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go deleted file mode 100644 index 1005f9fbd84ea..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_watch.go +++ /dev/null @@ -1,41 +0,0 @@ -// 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, pass string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &repos) -} - -// WatchRepo start to watch a repository -func (c *Client) WatchRepo(user, pass, repoUser, repoName string) (*WatchInfo, error) { - i := new(WatchInfo) - return i, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, i) -} - -// UnWatchRepo start to watch a repository -func (c *Client) UnWatchRepo(user, pass, repoUser, repoName string) (int, error) { - return c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil) -} diff --git a/vendor/code.gitea.io/sdk/gitea/status.go b/vendor/code.gitea.io/sdk/gitea/status.go deleted file mode 100644 index 3060ab1b2b23b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/status.go +++ /dev/null @@ -1,97 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` -} - -// 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"` -} - -// 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"` -} - -// ListStatusesOption holds pagination information -type ListStatusesOption struct { - Page int -} - -// CreateStatus creates a new Status for a given Commit -// -// POST /repos/:owner/:repo/statuses/:sha -func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { - body, err := json.Marshal(&opts) - if err != nil { - return nil, err - } - status := &Status{} - return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), - jsonHeader, bytes.NewReader(body), status) -} - -// ListStatuses returns all statuses for a given Commit -// -// GET /repos/:owner/:repo/commits/:ref/statuses -func (c *Client) ListStatuses(owner, repo, sha string, opts ListStatusesOption) ([]*Status, error) { - statuses := make([]*Status, 0, 10) - return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?page=%d", owner, repo, sha, opts.Page), nil, nil, &statuses) -} - -// GetCombinedStatus returns the CombinedStatus for a given Commit -// -// GET /repos/:owner/:repo/commits/:ref/status -func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { - status := &CombinedStatus{} - 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 deleted file mode 100644 index 57cf752316660..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user.go +++ /dev/null @@ -1,51 +0,0 @@ -// 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 ( - "encoding/json" - "fmt" -) - -// User represents a user -// swagger:model -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"` - // swagger:strfmt email - Email string `json:"email"` - // URL to the user's avatar - AvatarURL string `json:"avatar_url"` - // User locale - Language string `json:"language"` -} - -// MarshalJSON implements the json.Marshaler interface for User, adding field(s) for backward compatibility -func (u User) MarshalJSON() ([]byte, error) { - // Re-declaring User to avoid recursion - type shadow User - return json.Marshal(struct { - shadow - CompatUserName string `json:"username"` - }{shadow(u), u.UserName}) -} - -// 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 deleted file mode 100644 index d3bfce971bad4..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_app.go +++ /dev/null @@ -1,63 +0,0 @@ -// 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/base64" - "encoding/json" - "fmt" - "net/http" -) - -// BasicAuthEncode generate base64 of basic auth head -func BasicAuthEncode(user, pass string) string { - return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass)) -} - -// AccessToken represents a API access token. -// swagger:response AccessToken -type AccessToken struct { - ID int64 `json:"id"` - Name string `json:"name"` - Sha1 string `json:"sha1"` -} - -// AccessTokenList represents a list of API access token. -// swagger:response AccessTokenList -type AccessTokenList []*AccessToken - -// ListAccessTokens lista all the access tokens of user -func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) { - tokens := make([]*AccessToken, 0, 10) - return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens) -} - -// CreateAccessTokenOption options when create access token -// swagger:parameters userCreateToken -type CreateAccessTokenOption struct { - Name string `json:"name" binding:"Required"` -} - -// CreateAccessToken create one access token with options -func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) { - body, err := json.Marshal(&opt) - if err != nil { - return nil, err - } - t := new(AccessToken) - return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user), - http.Header{ - "content-type": []string{"application/json"}, - "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, - bytes.NewReader(body), t) -} - -// DeleteAccessToken delete token with key id -func (c *Client) DeleteAccessToken(user string, keyID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, 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 deleted file mode 100644 index 721f52144ba11..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_email.go +++ /dev/null @@ -1,56 +0,0 @@ -// 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" -) - -// Email an email address belonging to a user -type Email struct { - // swagger:strfmt email - Email string `json:"email"` - Verified bool `json:"verified"` - Primary bool `json:"primary"` -} - -// ListEmails all the email addresses of user -func (c *Client) ListEmails() ([]*Email, error) { - emails := make([]*Email, 0, 3) - return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails) -} - -// 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 deleted file mode 100644 index a197a7f188220..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_follow.go +++ /dev/null @@ -1,55 +0,0 @@ -// 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" - -// ListMyFollowers list all the followers of current user -func (c *Client) ListMyFollowers(page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users) -} - -// ListFollowers list all the followers of one user -func (c *Client) ListFollowers(user string, page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users) -} - -// ListMyFollowing list all the users current user followed -func (c *Client) ListMyFollowing(page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users) -} - -// ListFollowing list all the users the user followed -func (c *Client) ListFollowing(user string, page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users) -} - -// 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 deleted file mode 100644 index 0817d89461a1c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go +++ /dev/null @@ -1,80 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` - // swagger:strfmt date-time - Expires time.Time `json:"expires_at,omitempty"` -} - -// GPGKeyEmail an email attached to a GPGKey -// swagger:model GPGKeyEmail -type GPGKeyEmail struct { - Email string `json:"email"` - Verified bool `json:"verified"` -} - -// CreateGPGKeyOption options create user GPG key -type CreateGPGKeyOption struct { - // An armored GPG key to add - // - // required: true - // unique: true - ArmoredKey string `json:"armored_public_key" binding:"Required"` -} - -// ListGPGKeys list all the GPG keys of the user -func (c *Client) ListGPGKeys(user string) ([]*GPGKey, error) { - keys := make([]*GPGKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys", user), nil, nil, &keys) -} - -// ListMyGPGKeys list all the GPG keys of current user -func (c *Client) ListMyGPGKeys() ([]*GPGKey, error) { - keys := make([]*GPGKey, 0, 10) - return keys, c.getParsedResponse("GET", "/user/gpg_keys", nil, nil, &keys) -} - -// 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) -} - -// 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 deleted file mode 100644 index 4488c033f1a37..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_key.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` -} - -// ListPublicKeys list all the public keys of the user -func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) { - keys := make([]*PublicKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys) -} - -// ListMyPublicKeys list all the public keys of current user -func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) { - keys := make([]*PublicKey, 0, 10) - return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys) -} - -// 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) -} - -// 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 deleted file mode 100644 index 65ab980d66f86..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_search.go +++ /dev/null @@ -1,14 +0,0 @@ -package gitea - -import "fmt" - -type searchUsersResponse struct { - Users []*User `json:"data"` -} - -// SearchUsers finds users by query -func (c *Client) SearchUsers(query string, limit int) ([]*User, error) { - resp := new(searchUsersResponse) - err := c.getParsedResponse("GET", fmt.Sprintf("/users/search?q=%s&limit=%d", query, limit), nil, nil, &resp) - return resp.Users, err -} diff --git a/vendor/code.gitea.io/sdk/gitea/utils.go b/vendor/code.gitea.io/sdk/gitea/utils.go deleted file mode 100644 index 80892a1e7a90b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/utils.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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 ( - "net/http" -) - -var jsonHeader = http.Header{"content-type": []string{"application/json"}} - -// Bool return address of bool value -func Bool(v bool) *bool { - return &v -} - -// String return address of string value -func String(v string) *string { - return &v -} - -// Int64 return address of int64 value -func Int64(v int64) *int64 { - return &v -} From 87140e946c62bc95ac22911f24f0111b1c118c9d Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 01:42:56 +0800 Subject: [PATCH 02/21] recovery vendor. Signed-off-by: BetaCat0 outman99@hotmail.com --- Gopkg.lock | 332 +---------- vendor/code.gitea.io/git/LICENSE | 20 + vendor/code.gitea.io/git/blob.go | 73 +++ vendor/code.gitea.io/git/command.go | 134 +++++ vendor/code.gitea.io/git/commit.go | 276 +++++++++ vendor/code.gitea.io/git/commit_archive.go | 37 ++ vendor/code.gitea.io/git/commit_info.go | 319 +++++++++++ vendor/code.gitea.io/git/doc.go | 5 + vendor/code.gitea.io/git/error.go | 66 +++ vendor/code.gitea.io/git/git.go | 91 +++ vendor/code.gitea.io/git/hook.go | 126 +++++ vendor/code.gitea.io/git/parse.go | 81 +++ vendor/code.gitea.io/git/repo.go | 287 ++++++++++ vendor/code.gitea.io/git/repo_blame.go | 24 + vendor/code.gitea.io/git/repo_branch.go | 123 ++++ vendor/code.gitea.io/git/repo_commit.go | 352 ++++++++++++ vendor/code.gitea.io/git/repo_hook.go | 15 + vendor/code.gitea.io/git/repo_object.go | 19 + vendor/code.gitea.io/git/repo_pull.go | 89 +++ vendor/code.gitea.io/git/repo_tag.go | 157 ++++++ vendor/code.gitea.io/git/repo_tree.go | 26 + vendor/code.gitea.io/git/sha1.go | 76 +++ vendor/code.gitea.io/git/signature.go | 58 ++ vendor/code.gitea.io/git/submodule.go | 79 +++ vendor/code.gitea.io/git/tag.go | 89 +++ vendor/code.gitea.io/git/tree.go | 72 +++ vendor/code.gitea.io/git/tree_blob.go | 59 ++ vendor/code.gitea.io/git/tree_entry.go | 200 +++++++ vendor/code.gitea.io/git/utils.go | 96 ++++ vendor/code.gitea.io/sdk/LICENSE | 20 + vendor/code.gitea.io/sdk/gitea/admin_org.go | 22 + vendor/code.gitea.io/sdk/gitea/admin_repo.go | 22 + vendor/code.gitea.io/sdk/gitea/admin_user.go | 82 +++ vendor/code.gitea.io/sdk/gitea/attachment.go | 92 +++ vendor/code.gitea.io/sdk/gitea/doc.go | 5 + vendor/code.gitea.io/sdk/gitea/fork.go | 39 ++ vendor/code.gitea.io/sdk/gitea/gitea.go | 104 ++++ vendor/code.gitea.io/sdk/gitea/hook.go | 531 ++++++++++++++++++ vendor/code.gitea.io/sdk/gitea/issue.go | 154 +++++ .../code.gitea.io/sdk/gitea/issue_comment.go | 76 +++ vendor/code.gitea.io/sdk/gitea/issue_label.go | 122 ++++ .../sdk/gitea/issue_milestone.go | 80 +++ .../sdk/gitea/issue_tracked_time.go | 68 +++ vendor/code.gitea.io/sdk/gitea/lfs_lock.go | 65 +++ .../code.gitea.io/sdk/gitea/miscellaneous.go | 52 ++ vendor/code.gitea.io/sdk/gitea/org.go | 68 +++ vendor/code.gitea.io/sdk/gitea/org_member.go | 26 + vendor/code.gitea.io/sdk/gitea/org_team.go | 32 ++ vendor/code.gitea.io/sdk/gitea/pull.go | 151 +++++ vendor/code.gitea.io/sdk/gitea/release.go | 105 ++++ vendor/code.gitea.io/sdk/gitea/repo.go | 155 +++++ vendor/code.gitea.io/sdk/gitea/repo_branch.go | 27 + .../sdk/gitea/repo_collaborator.go | 57 ++ vendor/code.gitea.io/sdk/gitea/repo_file.go | 15 + vendor/code.gitea.io/sdk/gitea/repo_key.go | 69 +++ vendor/code.gitea.io/sdk/gitea/repo_watch.go | 41 ++ vendor/code.gitea.io/sdk/gitea/status.go | 97 ++++ vendor/code.gitea.io/sdk/gitea/user.go | 51 ++ vendor/code.gitea.io/sdk/gitea/user_app.go | 63 +++ vendor/code.gitea.io/sdk/gitea/user_email.go | 56 ++ vendor/code.gitea.io/sdk/gitea/user_follow.go | 55 ++ vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 80 +++ vendor/code.gitea.io/sdk/gitea/user_key.go | 57 ++ vendor/code.gitea.io/sdk/gitea/user_search.go | 14 + vendor/code.gitea.io/sdk/gitea/utils.go | 26 + .../Unknwon/cae/tz/testdata/test.lnk | 1 - .../Unknwon/cae/tz/testdata/testdir.lnk | 1 - .../Unknwon/cae/zip/testdata/test.lnk | 1 - .../Unknwon/cae/zip/testdata/testdir.lnk | 1 - vendor/gopkg.in/macaron.v1/fixtures/symlink | 1 - 70 files changed, 5847 insertions(+), 318 deletions(-) create mode 100644 vendor/code.gitea.io/git/LICENSE create mode 100644 vendor/code.gitea.io/git/blob.go create mode 100644 vendor/code.gitea.io/git/command.go create mode 100644 vendor/code.gitea.io/git/commit.go create mode 100644 vendor/code.gitea.io/git/commit_archive.go create mode 100644 vendor/code.gitea.io/git/commit_info.go create mode 100644 vendor/code.gitea.io/git/doc.go create mode 100644 vendor/code.gitea.io/git/error.go create mode 100644 vendor/code.gitea.io/git/git.go create mode 100644 vendor/code.gitea.io/git/hook.go create mode 100644 vendor/code.gitea.io/git/parse.go create mode 100644 vendor/code.gitea.io/git/repo.go create mode 100644 vendor/code.gitea.io/git/repo_blame.go create mode 100644 vendor/code.gitea.io/git/repo_branch.go create mode 100644 vendor/code.gitea.io/git/repo_commit.go create mode 100644 vendor/code.gitea.io/git/repo_hook.go create mode 100644 vendor/code.gitea.io/git/repo_object.go create mode 100644 vendor/code.gitea.io/git/repo_pull.go create mode 100644 vendor/code.gitea.io/git/repo_tag.go create mode 100644 vendor/code.gitea.io/git/repo_tree.go create mode 100644 vendor/code.gitea.io/git/sha1.go create mode 100644 vendor/code.gitea.io/git/signature.go create mode 100644 vendor/code.gitea.io/git/submodule.go create mode 100644 vendor/code.gitea.io/git/tag.go create mode 100644 vendor/code.gitea.io/git/tree.go create mode 100644 vendor/code.gitea.io/git/tree_blob.go create mode 100644 vendor/code.gitea.io/git/tree_entry.go create mode 100644 vendor/code.gitea.io/git/utils.go create mode 100644 vendor/code.gitea.io/sdk/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/doc.go create mode 100644 vendor/code.gitea.io/sdk/gitea/fork.go create mode 100644 vendor/code.gitea.io/sdk/gitea/gitea.go 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_tracked_time.go create mode 100644 vendor/code.gitea.io/sdk/gitea/lfs_lock.go create mode 100644 vendor/code.gitea.io/sdk/gitea/miscellaneous.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/pull.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_collaborator.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_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/utils.go delete mode 120000 vendor/github.com/Unknwon/cae/tz/testdata/test.lnk delete mode 120000 vendor/github.com/Unknwon/cae/tz/testdata/testdir.lnk delete mode 120000 vendor/github.com/Unknwon/cae/zip/testdata/test.lnk delete mode 120000 vendor/github.com/Unknwon/cae/zip/testdata/testdir.lnk delete mode 120000 vendor/gopkg.in/macaron.v1/fixtures/symlink diff --git a/Gopkg.lock b/Gopkg.lock index 04c7d18334ae8..9076a0c839a0a 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,86 +3,65 @@ [[projects]] branch = "master" - digest = "1:42f77a668e3bd06812ef254f334d0d0a62346969fbcd3fa3a613e75067343751" name = "code.gitea.io/git" packages = ["."] - pruneopts = "NUT" revision = "31f4b8e8c805438ac6d8914b38accb1d8aaf695e" [[projects]] branch = "master" - digest = "1:5e7f14543006a44047fb1d0df16da08b2ebc2428f1fd53bd8af26a2b34928b11" name = "code.gitea.io/sdk" packages = ["gitea"] - pruneopts = "NUT" revision = "021567c9c12fe289b8980c34e81e6684434dd082" [[projects]] - digest = "1:3fcef06a1a6561955c94af6c7757a6fa37605eb653f0d06ab960e5bb80092195" name = "github.com/PuerkitoBio/goquery" packages = ["."] - pruneopts = "NUT" revision = "ed7d758e9a34ba1f55e8084e0d731448b46921a8" [[projects]] - digest = "1:44121ca443aec4512ceaeec5047d0162b86bfcc26f35eadddda93bc265cb2e39" name = "github.com/RoaringBitmap/roaring" packages = ["."] - pruneopts = "NUT" revision = "1a28a7fa985680f9f4e1644c0a857ec359a444b0" version = "v0.4.7" [[projects]] branch = "master" - digest = "1:93367b6d47a8ccc7d14f9f493ccf103ccf5afb698559ff8e8f1999427ce27ace" name = "github.com/Smerity/govarint" packages = ["."] - pruneopts = "NUT" revision = "7265e41f48f15fd61751e16da866af3c704bb3ab" [[projects]] branch = "master" - digest = "1:d290f4b25abbf574f80f60c8a5603ddada784f13f436b91a9a927bc7ce5a0146" name = "github.com/Unknwon/cae" packages = [ ".", - "zip", + "zip" ] - pruneopts = "NUT" revision = "c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c" [[projects]] branch = "master" - digest = "1:7d23e6e1889b8bb4bbb37a564708fdab4497ce232c3a99d66406c975b642a6ff" name = "github.com/Unknwon/com" packages = ["."] - pruneopts = "NUT" revision = "7677a1d7c1137cd3dd5ba7a076d0c898a1ef4520" [[projects]] branch = "master" - digest = "1:a89bad9aea65873d45195417902ba1e6245114bdf1005d855909a7725b0361d1" name = "github.com/Unknwon/i18n" packages = ["."] - pruneopts = "NUT" revision = "b64d336589669d317928070e70ba0ae558f16633" [[projects]] - digest = "1:d311c4c0cfd13f237665b248a55c909d5b40815c06f28992f35cba3266ef27da" name = "github.com/Unknwon/paginater" packages = ["."] - pruneopts = "NUT" revision = "7748a72e01415173a27d79866b984328e7b0c12b" [[projects]] - digest = "1:fc86904a62ac4bfff8cfbe94f42231ce3d8cea8fe2506d5293eaef468f8eaecf" name = "github.com/andybalholm/cascadia" packages = ["."] - pruneopts = "NUT" revision = "349dd0209470eabd9514242c688c403c0926d266" [[projects]] - digest = "1:67351095005f164e748a5a21899d1403b03878cb2d40a7b0f742376e6eeda974" name = "github.com/blevesearch/bleve" packages = [ ".", @@ -124,353 +103,265 @@ "search/highlight/highlighter/simple", "search/query", "search/scorer", - "search/searcher", + "search/searcher" ] - pruneopts = "NUT" revision = "ff210fbc6d348ad67aa5754eaea11a463fcddafd" [[projects]] branch = "master" - digest = "1:b165e3f145596f4ff864a34e38e0b63c8e57bbaec2d5a234f234f7554b84c42b" name = "github.com/blevesearch/go-porterstemmer" packages = ["."] - pruneopts = "NUT" revision = "23a2c8e5cf1f380f27722c6d2ae8896431dc7d0e" [[projects]] - digest = "1:a64956a7766e0d081ebff30d8528db107118485d2ee89cab751e6506f5ab55ea" name = "github.com/blevesearch/segment" packages = ["."] - pruneopts = "NUT" revision = "db70c57796cc8c310613541dfade3dce627d09c7" [[projects]] - digest = "1:c7e0968c05659f3973148cd5c5387d6ee960a6ae1b2eaaec0b1d435d806458bb" name = "github.com/boltdb/bolt" packages = ["."] - pruneopts = "NUT" revision = "ccd680d8c1a0179ac3d68f692b01e1a1589cbfc7" source = "github.com/go-gitea/bolt" [[projects]] - digest = "1:7c96cf7bf7f52af67f7a8222185813b9b665f5172ec2ac5f7d49ed96e5fcf3e5" name = "github.com/boombuler/barcode" packages = [ ".", "qr", - "utils", + "utils" ] - pruneopts = "NUT" revision = "fe0f26ff6d26693948ee8189aa064ee8c54141fa" [[projects]] - digest = "1:867be5f6a8d3bf4525390559899af512f48675932e2cc3cbaa2304e9c75fc1ba" name = "github.com/bradfitz/gomemcache" packages = ["memcache"] - pruneopts = "NUT" revision = "fb1f79c6b65acda83063cbc69f6bba1522558bfc" [[projects]] - digest = "1:ce4ec45b1c748a187386bfb3adc6b78f07a3c6cecc689f7bf68dd0d3630c6d58" name = "github.com/chaseadamsio/goorgeous" packages = ["."] - pruneopts = "NUT" revision = "098da33fde5f9220736531b3cb26a2dec86a8367" [[projects]] branch = "master" - digest = "1:82e1ad11d777f7bff9a1fc678a8a534a318f85e5026a8a4d6f4a94a6b0678bb6" name = "github.com/couchbase/vellum" packages = [ ".", "regexp", - "utf8", + "utf8" ] - pruneopts = "NUT" revision = "eb6ae3743b3f300f2136f83ca78c08cc071edbd4" [[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "NUT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:08c314ceab5d0a82739bb0846a5d764bed6f1294610e79b651a4c08671830ecb" name = "github.com/denisenkom/go-mssqldb" packages = ["."] - pruneopts = "NUT" revision = "e32ca5036449b7ea12c62ed761ea1ad7fc88a4e2" [[projects]] - digest = "1:01ced7908dbaae42990af9521328922b8948bdcb174c23bba6db572381515716" name = "github.com/dgrijalva/jwt-go" packages = ["."] - pruneopts = "NUT" revision = "9ed569b5d1ac936e6494082958d63a6aa4fff99a" [[projects]] branch = "master" - digest = "1:7e2a28602fd65774c79a780a9c32a7a82d180e5a93bb5a36a6beb8619e24a35b" name = "github.com/edsrzf/mmap-go" packages = ["."] - pruneopts = "NUT" revision = "0bce6a6887123b67a60366d2c9fe2dfb74289d2e" [[projects]] - digest = "1:9b7f3250d2bd2c70fef82ff79a1c43cfacedd114288af3b86da0c31c67756a2f" name = "github.com/elazarl/go-bindata-assetfs" packages = ["."] - pruneopts = "NUT" revision = "57eb5e1fc594ad4b0b1dbea7b286d299e0cb43c2" [[projects]] - digest = "1:8603f74d35c93b37c615a02ba297be2cf2efc9ff6f1ff2b458a903990b568e48" name = "github.com/ethantkoenig/rupture" packages = ["."] - pruneopts = "NUT" revision = "0a76f03a811abcca2e6357329b673e9bb8ef9643" [[projects]] branch = "master" - digest = "1:b29ac3fe6b4601f89b589337c584ab7204a5c72932465e5f4a16772b5560b4a7" name = "github.com/facebookgo/clock" packages = ["."] - pruneopts = "NUT" revision = "600d898af40aa09a7a93ecb9265d87b0504b6f03" [[projects]] - digest = "1:ee3e74e7e3789fc2de1479146477b5cc31f9344dfe2772c01a967a13552c7e60" name = "github.com/facebookgo/grace" packages = [ "gracehttp", - "gracenet", + "gracenet" ] - pruneopts = "NUT" revision = "5729e484473f52048578af1b80d0008c7024089b" [[projects]] branch = "master" - digest = "1:ff3883a000118ba7efd4c41cc4656592e97d3a0860225d5f087a194066685ce4" name = "github.com/facebookgo/httpdown" packages = ["."] - pruneopts = "NUT" revision = "a3b1354551a26449fbe05f5d855937f6e7acbd71" [[projects]] branch = "master" - digest = "1:35a271df55b343e440407daac25d877269e3bb2f60d2031bcc339bcbe6c0f9b9" name = "github.com/facebookgo/stats" packages = ["."] - pruneopts = "NUT" revision = "1b76add642e42c6ffba7211ad7b3939ce654526e" [[projects]] branch = "master" - digest = "1:ccee1c7954f7296e324a0832b7a4a0a38ea7e51145375fd837283652366c3653" name = "github.com/glycerine/go-unsnap-stream" packages = ["."] - pruneopts = "NUT" revision = "9f0cb55181dd3a0a4c168d3dbc72d4aca4853126" [[projects]] branch = "master" - digest = "1:1961e20504ac246a7eacff00a56ce75cd60be05ea38e04381663593ba5879f58" name = "github.com/go-macaron/bindata" packages = ["."] - pruneopts = "NUT" revision = "85786f57eee3e5544a9cc24fa2afe425b97a8652" [[projects]] - digest = "1:628de1525ac764bbe390376679e1ee0ea538429c207926eadf66bdeccda1bf89" name = "github.com/go-macaron/binding" packages = ["."] - pruneopts = "NUT" revision = "9440f336b443056c90d7d448a0a55ad8c7599880" [[projects]] branch = "master" - digest = "1:2440f13a7c7b8a7620bf71504c41a5efb6e04a01249d4eba8b9ce00d2575e793" name = "github.com/go-macaron/cache" packages = [ ".", "memcache", - "redis", + "redis" ] - pruneopts = "NUT" revision = "56173531277692bc2925924d51fda1cd0a6b8178" [[projects]] - digest = "1:221be3922b1be8fe9405a73fd030efe0585baaa41fe9828768ac245c6ea53a83" name = "github.com/go-macaron/captcha" packages = ["."] - pruneopts = "NUT" revision = "8aa5919789ab301e865595eb4b1114d6b9847deb" [[projects]] branch = "master" - digest = "1:7ae1d1b3a156d71413b3a35ef6cf2b1fd6f91e6db0b6f1e8a5f69b47a46795d9" name = "github.com/go-macaron/csrf" packages = ["."] - pruneopts = "NUT" revision = "503617c6b37257a55dff6293ec28556506c3a9a8" [[projects]] branch = "master" - digest = "1:6326b27f8e0c8e135c8674ddbc619fae879664ac832e8e6fa6a23ce0d279ed4d" name = "github.com/go-macaron/gzip" packages = ["."] - pruneopts = "NUT" revision = "cad1c6580a07c56f5f6bc52d66002a05985c5854" [[projects]] branch = "master" - digest = "1:d09d3c94e1bd444464c221be961ba4005e119308f1bcd57aa5f49046fb6affd2" name = "github.com/go-macaron/i18n" packages = ["."] - pruneopts = "NUT" revision = "ef57533c3b0fc2d8581deda14937e52f11a203ab" [[projects]] branch = "master" - digest = "1:fb8711b648d1ff03104fc1d9593a13cb1d5120be7ba2b01641c14ccae286a9e3" name = "github.com/go-macaron/inject" packages = ["."] - pruneopts = "NUT" revision = "d8a0b8677191f4380287cfebd08e462217bac7ad" [[projects]] - digest = "1:b327ca585509a889130a8f51f43704a8fe03cb5cd281dbf1bc6405f5a7ea4702" name = "github.com/go-macaron/session" packages = [ ".", - "redis", + "redis" ] - pruneopts = "NUT" revision = "66031fcb37a0fff002a1f028eb0b3a815c78306b" [[projects]] - digest = "1:6fb9cae2a3b4518e048a899b273e23b671802b611ccfcca0b576ecc08bb7b8f5" name = "github.com/go-macaron/toolbox" packages = ["."] - pruneopts = "NUT" revision = "99a42f20e9e88daec5c0d7beb4e7eac134680ab0" [[projects]] - digest = "1:747c1fcb10f8f6734551465ab73c6ed9c551aa6e66250fb6683d1624f554546a" name = "github.com/go-sql-driver/mysql" packages = ["."] - pruneopts = "NUT" revision = "d523deb1b23d913de5bdada721a6071e71283618" [[projects]] - digest = "1:1397763fd29d5667bcfbacde8a37542ee145416b3acb7e1b149c98fef2567930" name = "github.com/go-xorm/builder" packages = ["."] - pruneopts = "NUT" revision = "dc8bf48f58fab2b4da338ffd25191905fd741b8f" version = "v0.3.0" [[projects]] - digest = "1:c910feae32bcc3cbf068c7263424d9f198da931c0cad909179621835e6f87cb8" name = "github.com/go-xorm/core" packages = ["."] - pruneopts = "NUT" revision = "c10e21e7e1cec20e09398f2dfae385e58c8df555" version = "v0.6.0" [[projects]] - digest = "1:22a1ac7f654095f6817076eb975368bab5481e42554d0121ea37e28a86a3f83d" name = "github.com/go-xorm/xorm" packages = ["."] - pruneopts = "NUT" revision = "ad69f7d8f0861a29438154bb0a20b60501298480" [[projects]] branch = "master" - digest = "1:5fdcd55bad5c103674364f4fdb1ad2541186d063300ab24a8f2bb1b31ae07bac" name = "github.com/gogits/chardet" packages = ["."] - pruneopts = "NUT" revision = "2404f777256163ea3eadb273dada5dcb037993c0" [[projects]] - digest = "1:ea030ad2f50b1ced1944914dd80c72e9ebd839fb564c7b8859e7a5d626c61c51" name = "github.com/gogits/cron" packages = ["."] - pruneopts = "NUT" revision = "7f3990acf1833faa5ebd0e86f0a4c72a4b5eba3c" [[projects]] - digest = "1:b64f9be717fdab5f75122dc3868e8ca9d003779b6bc55f64f39a0cddc698bf88" name = "github.com/golang/protobuf" packages = ["proto"] - pruneopts = "NUT" revision = "99511271042a09d1e01baea8781caa5210fec66e" [[projects]] - digest = "1:60e25fc5f5cfd7783f985ca99b4383e848981dddf0be584db7d809be20848e25" name = "github.com/golang/snappy" packages = ["."] - pruneopts = "NUT" revision = "5f1c01d9f64b941dd9582c638279d046eda6ca31" [[projects]] - digest = "1:c01767916c59f084bb7c41a7d5877c0f3099b1595cfa066e84ec6ad6b084dd89" name = "github.com/gorilla/context" packages = ["."] - pruneopts = "NUT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - digest = "1:9ad9280c98033812aec525d43d4e8137021642dc942bf271b4710f9ac93d0d0b" name = "github.com/gorilla/mux" packages = ["."] - pruneopts = "NUT" revision = "757bef944d0f21880861c2dd9c871ca543023cba" [[projects]] - digest = "1:0faa8131e5822f3420f82426667a29c5c425c3cb7e0fcf0c5d1c718d6e6ba19b" name = "github.com/gorilla/securecookie" packages = ["."] - pruneopts = "NUT" revision = "e59506cc896acb7f7bf732d4fdf5e25f7ccd8983" version = "v1.1.1" [[projects]] - digest = "1:ee5531f1e32c0082a6da68a605bc60284711d99b15d38dfba335a1ec52a58c20" name = "github.com/gorilla/sessions" packages = ["."] - pruneopts = "NUT" revision = "ca9ada44574153444b00d3fd9c8559e4cc95f896" version = "v1.1" [[projects]] - digest = "1:18231f2a4af6633fbcd94baab40320d16e826a7f732094ba3420ab547206949b" name = "github.com/issue9/identicon" packages = ["."] - pruneopts = "NUT" revision = "d36b54562f4cf70c83653e13dc95c220c79ef521" [[projects]] - digest = "1:d2d4f736f81c5312e2b885798f8a33f9819c6217664404d5b9a4088fcd606df4" name = "github.com/jaytaylor/html2text" packages = ["."] - pruneopts = "NUT" revision = "8fb95d837f7d6db1913fecfd7bcc5333e6499596" [[projects]] - digest = "1:6342cf70eaae592f7b8e2552037f2a9d4d16fa321c6e36f09c3bc450add2de19" name = "github.com/kballard/go-shellquote" packages = ["."] - pruneopts = "NUT" revision = "cd60e84ee657ff3dc51de0b4f55dd299a3e136f2" [[projects]] - digest = "1:b32126992771fddadf6a778fe7ab29150665ed78f31ce4eb550a9db3bc0e650c" name = "github.com/keybase/go-crypto" packages = [ "brainpool", @@ -485,69 +376,55 @@ "openpgp/errors", "openpgp/packet", "openpgp/s2k", - "rsa", + "rsa" ] - pruneopts = "NUT" revision = "00ac4db533f63ef97576cbc7b07939ff7daf7329" [[projects]] - digest = "1:c5e37ea5ada80299e6a8e7ebc1a47999c2c8a53eac3a455168adcdcdc78dc93a" name = "github.com/klauspost/compress" packages = [ "flate", - "gzip", + "gzip" ] - pruneopts = "NUT" revision = "8df558b6cb6f9b445f9586446cfe7223e7d8bd6b" version = "v1.1" [[projects]] - digest = "1:6a2949d9a141c72cfaa5b55c65794d9b1179878fccdcae735ab62be27bf9cf34" name = "github.com/klauspost/cpuid" packages = ["."] - pruneopts = "NUT" revision = "09cded8978dc9e80714c4d85b0322337b0a1e5e0" version = "v1.0" [[projects]] - digest = "1:b95da1293525625ef6f07be79d537b9bf2ecd7901efcf9a92193edafbd55b9ef" name = "github.com/klauspost/crc32" packages = ["."] - pruneopts = "NUT" revision = "cb6bfca970f6908083f26f39a79009d608efd5cd" version = "v1.1" [[projects]] - digest = "1:38fc7fe0f78eaecdf1ab39a60ba49df85405597103f38d07f2ac560e7e4c8443" name = "github.com/lafriks/xormstore" packages = [ ".", - "util", + "util" ] - pruneopts = "NUT" revision = "9cab149ea91875cf056211bd6ef82379fce9cb67" version = "v1.0.0" [[projects]] - digest = "1:f1105223bc7ff6a3f3074cf6cccc6c8362ff23db1e7d8505dda01fc4b79b8005" name = "github.com/lib/pq" packages = [ ".", - "oid", + "oid" ] - pruneopts = "NUT" revision = "456514e2defec52e0cd37f90ccf17ec8b28295e2" [[projects]] branch = "master" - digest = "1:6e81c70f78cdc298ea6f19fa9bdba95aacd13a0e0ddb7e118046113997d4dafb" name = "github.com/lunny/dingtalk_webhook" packages = ["."] - pruneopts = "NUT" revision = "e3534c89ef969912856dfa39e56b09e58c5f5daf" [[projects]] - digest = "1:fb22af9d8c1a6166ad299705648db460ba2c28a830f7f6cdd830019d7c3fd96f" name = "github.com/markbates/goth" packages = [ ".", @@ -559,175 +436,131 @@ "providers/gitlab", "providers/gplus", "providers/openidConnect", - "providers/twitter", + "providers/twitter" ] - pruneopts = "NUT" revision = "4933f155d89c3c52ab4ca545c6602cf4a1e87913" version = "1.45.5" [[projects]] - digest = "1:3ef954101983406a71171c4dc816a73e01bb3de608b3dd063627aa67a459f3e3" name = "github.com/mattn/go-sqlite3" packages = ["."] - pruneopts = "NUT" revision = "acfa60124032040b9f5a9406f5a772ee16fe845e" [[projects]] branch = "master" - digest = "1:1ed0f3c066eb9d1c2ff7a864a6fa595c70b9b49049cc46af6a6f7ff0e4655321" name = "github.com/mcuadros/go-version" packages = ["."] - pruneopts = "NUT" revision = "88e56e02bea1c203c99222c365fa52a69996ccac" [[projects]] - digest = "1:f2111ff3f139dacf8b2177e32f296ad20df85d6ec0ee0e2e348f0fcb21186c14" name = "github.com/microcosm-cc/bluemonday" packages = ["."] - pruneopts = "NUT" revision = "f77f16ffc87a6a58814e64ae72d55f9c41374e6d" [[projects]] - digest = "1:c7dc71a7e144df03332152d730f9c5ae22cf1cfd55454cb001ba8ffcb78aa7f0" name = "github.com/mrjones/oauth" packages = ["."] - pruneopts = "NUT" revision = "3f67d9c274355678b2f9844b08d643e2f9213340" [[projects]] branch = "master" - digest = "1:874d20d479aa479b2ed0200ac565e809d8ff849f672a04e7a21536069eba1cdd" name = "github.com/mschoch/smat" packages = ["."] - pruneopts = "NUT" revision = "90eadee771aeab36e8bf796039b8c261bebebe4f" [[projects]] - digest = "1:15bc31ae39f989dda613930c1de860aced7b922502f8d9d861998fc195b7937c" name = "github.com/msteinert/pam" packages = ["."] - pruneopts = "NUT" revision = "02ccfbfaf0cc627aa3aec8ef7ed5cfeec5b43f63" [[projects]] - digest = "1:2be1d891535ce3d6d2a3db9087f07415e909744e9eff1a30f8f0b2519df60ae6" name = "github.com/nfnt/resize" packages = ["."] - pruneopts = "NUT" revision = "891127d8d1b52734debe1b3c3d7e747502b6c366" [[projects]] - digest = "1:44c66ad69563dbe3f8e76d7d6cad21a03626e53f1875b5ab163ded419e01ca7a" name = "github.com/philhofer/fwd" packages = ["."] - pruneopts = "NUT" revision = "bb6d471dc95d4fe11e432687f8b70ff496cf3136" version = "v1.0.0" [[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "NUT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:aabb118251a9ee8ddab44c405f2391852a82dcf33358cda25ea5748561411ffc" name = "github.com/pquerna/otp" packages = [ ".", "hotp", - "totp", + "totp" ] - pruneopts = "NUT" revision = "54653902c20e47f3417541d35435cb6d6162e28a" [[projects]] branch = "master" - digest = "1:5be01c22bc1040e2f6ce4755d51a0ac9cef823a9f2004fb1f9896a414ef519e6" name = "github.com/russross/blackfriday" packages = ["."] - pruneopts = "NUT" revision = "11635eb403ff09dbc3a6b5a007ab5ab09151c229" [[projects]] - digest = "1:54f275b550b8a8a20bc91e2067ed740600b69dae9dcf9cdfe905bac1b9cfd1d0" name = "github.com/satori/go.uuid" packages = ["."] - pruneopts = "NUT" revision = "b061729afc07e77a8aa4fad0a2fd840958f1942a" [[projects]] - digest = "1:3e0777ad56c86a93cf22459acca84d5c3c8a86b163362074dcb7b33c01aba82b" name = "github.com/sergi/go-diff" packages = ["diffmatchpatch"] - pruneopts = "NUT" revision = "552b4e9bbdca9e5adafd95ee98c822fdd11b330b" [[projects]] - digest = "1:400359f0b394fb168f4aee9621d42cc005810c6e462009d5fc76055d5e96dcf3" name = "github.com/shurcooL/sanitized_anchor_name" packages = ["."] - pruneopts = "NUT" revision = "1dba4b3954bc059efc3991ec364f9f9a35f597d2" [[projects]] branch = "master" - digest = "1:69177343ca227319b4580441a67d9d889e9ac7fcbfb89fbaa36d3283e6ab0139" name = "github.com/steveyen/gtreap" packages = ["."] - pruneopts = "NUT" revision = "0abe01ef9be25c4aedc174758ec2d917314d6d70" [[projects]] - digest = "1:a852b1ad03ca063d2c57866d9f94dcb1cb2e111415c5902ce0586fc2d207221b" name = "github.com/stretchr/testify" packages = ["assert"] - pruneopts = "NUT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" - digest = "1:3cb6dfe7cdece5716b1c3c3c0b5faf7fce2e83e2758e2baad2e9986d101980b8" name = "github.com/tinylib/msgp" packages = ["msgp"] - pruneopts = "NUT" revision = "c8cf64dff2009d53fa8f8a16df54d1cdfc64c4a7" [[projects]] branch = "master" - digest = "1:aa8ce6454cff67af88a195977ba6489df6c55802e1199cbe24af9febec8c1586" name = "github.com/tstranex/u2f" packages = ["."] - pruneopts = "NUT" revision = "d21a03e0b1d9fc1df59ff54e7a513655c1748b0c" [[projects]] - digest = "1:d9f3ecc1fb41eaf8af777f844a2c0eb9b7ff743224981e5af4ade023210cf6e5" name = "github.com/urfave/cli" packages = ["."] - pruneopts = "NUT" revision = "d86a009f5e13f83df65d0d6cee9a2e3f1445f0da" [[projects]] branch = "master" - digest = "1:1d786f876a94d808e0ee5052e1f65ab284dc7483a7517d76d25baa8099429ed5" name = "github.com/willf/bitset" packages = ["."] - pruneopts = "NUT" revision = "8ce1146b8621c95164efd9c8b1124cfa9b8afb4e" [[projects]] - digest = "1:27d050258a4b19ca3b7a1bf26f4a04c5c66bbf0670b346ee509ebb0ad82257a6" name = "github.com/yohcop/openid-go" packages = ["."] - pruneopts = "NUT" revision = "2c050d2dae5345c417db301f11fda6fbf5ad0f0a" [[projects]] - digest = "1:e4ea859df4986eb46feebbb84a2d163a4a314e87668177ca13b3b0adecaf50e8" name = "golang.org/x/crypto" packages = [ "acme", @@ -739,53 +572,43 @@ "md4", "pbkdf2", "poly1305", - "ssh", + "ssh" ] - pruneopts = "NUT" revision = "12dd70caea0268ac0d6c2707d0611ef601e7c64e" [[projects]] - digest = "1:47ea747d07fae720d749d06ac5dc5ded0df70c57e328b6549cf2d9c64698757e" name = "golang.org/x/net" packages = [ "context", "html", "html/atom", - "html/charset", + "html/charset" ] - pruneopts = "NUT" revision = "f2499483f923065a842d38eb4c7f1927e6fc6e6d" [[projects]] - digest = "1:8159a9cda4b8810aaaeb0d60e2fa68e2fd86d8af4ec8f5059830839e3c8d93d5" name = "golang.org/x/oauth2" packages = [ ".", - "internal", + "internal" ] - pruneopts = "NUT" revision = "c10ba270aa0bf8b8c1c986e103859c67a9103061" [[projects]] - digest = "1:9f303486d623f840492bfeb48eb906a94e9d3fe638a761639b72ce64bf7bfcc3" name = "golang.org/x/sync" packages = ["syncmap"] - pruneopts = "NUT" revision = "5a06fca2c336a4b2b2fcb45702e8c47621b2aa2c" [[projects]] - digest = "1:47495898c42062ace16d8046915b088e7c3846e77b997ec5a8a00ec552e179d5" name = "golang.org/x/sys" packages = [ "unix", "windows", - "windows/svc", + "windows/svc" ] - pruneopts = "NUT" revision = "a646d33e2ee3172a661fc09bca23bb4889a41bc8" [[projects]] - digest = "1:d2463fd72ee2636c3d9bbdb98fa4996a118f210ae3e5eaf62d281855bc0b4a83" name = "golang.org/x/text" packages = [ "encoding", @@ -807,200 +630,83 @@ "runes", "transform", "unicode/cldr", - "unicode/norm", + "unicode/norm" ] - pruneopts = "NUT" revision = "2bf8f2a19ec09c670e931282edfe6567f6be21c9" [[projects]] branch = "v3" - digest = "1:1244a9b3856f70d5ffb74bbfd780fc9d47f93f2049fa265c6fb602878f507bf8" name = "gopkg.in/alexcesaro/quotedprintable.v3" packages = ["."] - pruneopts = "NUT" revision = "2caba252f4dc53eaf6b553000885530023f54623" [[projects]] - digest = "1:9c577b4736db46066c2a41aef5736316fc5e0c8d1b97e8917f4b6157b530ee53" name = "gopkg.in/asn1-ber.v1" packages = ["."] - pruneopts = "NUT" revision = "4e86f4367175e39f69d9358a5f17b4dda270378d" version = "v1.1" [[projects]] - digest = "1:24bfc2e8bf971485cb5ba0f0e5b08a1b806cca5828134df76b32d1ea50f2ab49" name = "gopkg.in/bufio.v1" packages = ["."] - pruneopts = "NUT" revision = "567b2bfa514e796916c4747494d6ff5132a1dfce" version = "v1" [[projects]] - digest = "1:9146e4250cb4359ac2f7a1ac3766dbcc52b3d8414ab9ac1af195ce6fba6c234f" name = "gopkg.in/editorconfig/editorconfig-core-go.v1" packages = ["."] - pruneopts = "NUT" revision = "a872f05c2e34b37b567401384d202aff11ba06d4" version = "v1.2.0" [[projects]] branch = "v2" - digest = "1:8db3ee13f824cd299f10af1dead41de8bce6b53a704998976e58c5b9274ab4b6" name = "gopkg.in/gomail.v2" packages = ["."] - pruneopts = "NUT" revision = "81ebce5c23dfd25c6c67194b37d3dd3f338c98b1" [[projects]] - digest = "1:cbecb8d0e314f34d1bc65a86cb433e33ad8e32c2cb6ae313a4f2e52806ddd984" name = "gopkg.in/ini.v1" packages = ["."] - pruneopts = "NUT" revision = "7e7da451323b6766da368f8a1e8ec9a88a16b4a0" version = "v1.31.1" [[projects]] - digest = "1:01f4ac37c52bda6f7e1bd73680a99f88733c0408aaa159ecb1ba53a1ade9423c" name = "gopkg.in/ldap.v2" packages = ["."] - pruneopts = "NUT" revision = "d0a5ced67b4dc310b9158d63a2c6f9c5ec13f105" version = "v2.4.1" [[projects]] - digest = "1:cfe1730a152ff033ad7d9c115d22e36b19eec6d5928c06146b9119be45d39dc0" name = "gopkg.in/macaron.v1" packages = ["."] - pruneopts = "NUT" revision = "75f2e9b42e99652f0d82b28ccb73648f44615faa" version = "v1.2.4" [[projects]] - digest = "1:00126f697efdcab42f07c89ac8bf0095fb2328aef6464e070055154088cea859" name = "gopkg.in/redis.v2" packages = ["."] - pruneopts = "NUT" revision = "e6179049628164864e6e84e973cfb56335748dea" version = "v2.3.2" [[projects]] - digest = "1:e2144032dcf8e856fb733151391669dc2d32d79ebb69e3c4151efa605f5e8a01" name = "gopkg.in/testfixtures.v2" packages = ["."] - pruneopts = "NUT" revision = "b9ef14dc461bf934d8df2dfc6f1f456be5664cca" version = "v2.0.0" [[projects]] - digest = "1:ad6f94355d292690137613735965bd3688844880fdab90eccf66321910344942" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "NUT" revision = "a5b47d31c556af34a302ce5d659e6fea44d90de0" [[projects]] - digest = "1:5972c0a5308529a35d87dd2dbba827625df90e6c89b0f496644fc43ea761bcf2" name = "strk.kbt.io/projects/go/libravatar" packages = ["."] - pruneopts = "NUT" revision = "5eed7bff870ae19ef51c5773dbc8f3e9fcbd0982" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "code.gitea.io/git", - "code.gitea.io/sdk/gitea", - "github.com/PuerkitoBio/goquery", - "github.com/Unknwon/cae/zip", - "github.com/Unknwon/com", - "github.com/Unknwon/i18n", - "github.com/Unknwon/paginater", - "github.com/blevesearch/bleve", - "github.com/blevesearch/bleve/analysis/analyzer/custom", - "github.com/blevesearch/bleve/analysis/token/camelcase", - "github.com/blevesearch/bleve/analysis/token/lowercase", - "github.com/blevesearch/bleve/analysis/token/unicodenorm", - "github.com/blevesearch/bleve/analysis/token/unique", - "github.com/blevesearch/bleve/analysis/tokenizer/unicode", - "github.com/blevesearch/bleve/index/upsidedown", - "github.com/blevesearch/bleve/mapping", - "github.com/blevesearch/bleve/search/query", - "github.com/chaseadamsio/goorgeous", - "github.com/denisenkom/go-mssqldb", - "github.com/dgrijalva/jwt-go", - "github.com/ethantkoenig/rupture", - "github.com/facebookgo/grace/gracehttp", - "github.com/go-macaron/bindata", - "github.com/go-macaron/binding", - "github.com/go-macaron/cache", - "github.com/go-macaron/cache/memcache", - "github.com/go-macaron/cache/redis", - "github.com/go-macaron/captcha", - "github.com/go-macaron/csrf", - "github.com/go-macaron/gzip", - "github.com/go-macaron/i18n", - "github.com/go-macaron/inject", - "github.com/go-macaron/session", - "github.com/go-macaron/session/redis", - "github.com/go-macaron/toolbox", - "github.com/go-sql-driver/mysql", - "github.com/go-xorm/builder", - "github.com/go-xorm/core", - "github.com/go-xorm/xorm", - "github.com/gogits/chardet", - "github.com/gogits/cron", - "github.com/gorilla/context", - "github.com/issue9/identicon", - "github.com/jaytaylor/html2text", - "github.com/kballard/go-shellquote", - "github.com/keybase/go-crypto/openpgp", - "github.com/keybase/go-crypto/openpgp/armor", - "github.com/keybase/go-crypto/openpgp/packet", - "github.com/lafriks/xormstore", - "github.com/lib/pq", - "github.com/lunny/dingtalk_webhook", - "github.com/markbates/goth", - "github.com/markbates/goth/gothic", - "github.com/markbates/goth/providers/bitbucket", - "github.com/markbates/goth/providers/dropbox", - "github.com/markbates/goth/providers/facebook", - "github.com/markbates/goth/providers/github", - "github.com/markbates/goth/providers/gitlab", - "github.com/markbates/goth/providers/gplus", - "github.com/markbates/goth/providers/openidConnect", - "github.com/markbates/goth/providers/twitter", - "github.com/mattn/go-sqlite3", - "github.com/mcuadros/go-version", - "github.com/microcosm-cc/bluemonday", - "github.com/msteinert/pam", - "github.com/nfnt/resize", - "github.com/pquerna/otp", - "github.com/pquerna/otp/totp", - "github.com/russross/blackfriday", - "github.com/satori/go.uuid", - "github.com/sergi/go-diff/diffmatchpatch", - "github.com/stretchr/testify/assert", - "github.com/tstranex/u2f", - "github.com/urfave/cli", - "github.com/yohcop/openid-go", - "golang.org/x/crypto/acme/autocert", - "golang.org/x/crypto/pbkdf2", - "golang.org/x/crypto/ssh", - "golang.org/x/net/html", - "golang.org/x/net/html/atom", - "golang.org/x/net/html/charset", - "golang.org/x/sync/syncmap", - "golang.org/x/sys/windows/svc", - "golang.org/x/text/transform", - "gopkg.in/editorconfig/editorconfig-core-go.v1", - "gopkg.in/gomail.v2", - "gopkg.in/ini.v1", - "gopkg.in/ldap.v2", - "gopkg.in/macaron.v1", - "gopkg.in/testfixtures.v2", - "strk.kbt.io/projects/go/libravatar", - ] + inputs-digest = "630dc9899a6e4c41863a8fa5c00b2017bc5bca748e3fad813bf8c3b8602a0d9f" solver-name = "gps-cdcl" solver-version = 1 diff --git a/vendor/code.gitea.io/git/LICENSE b/vendor/code.gitea.io/git/LICENSE new file mode 100644 index 0000000000000..10aeba46bcfc9 --- /dev/null +++ b/vendor/code.gitea.io/git/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/git/blob.go b/vendor/code.gitea.io/git/blob.go new file mode 100644 index 0000000000000..a6e392eeb50a6 --- /dev/null +++ b/vendor/code.gitea.io/git/blob.go @@ -0,0 +1,73 @@ +// 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 git + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "os" + "os/exec" +) + +// Blob represents a Git object. +type Blob struct { + repo *Repository + *TreeEntry +} + +// Data gets content of blob all at once and wrap it as io.Reader. +// This can be very slow and memory consuming for huge content. +func (b *Blob) Data() (io.Reader, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + + // Preallocate memory to save ~50% memory usage on big files. + stdout.Grow(int(b.Size() + 2048)) + + if err := b.DataPipeline(stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + return stdout, nil +} + +// DataPipeline gets content of blob and write the result or error to stdout or stderr +func (b *Blob) DataPipeline(stdout, stderr io.Writer) error { + return NewCommand("show", b.ID.String()).RunInDirPipeline(b.repo.Path, stdout, stderr) +} + +type cmdReadCloser struct { + cmd *exec.Cmd + stdout io.Reader +} + +func (c cmdReadCloser) Read(p []byte) (int, error) { + return c.stdout.Read(p) +} + +func (c cmdReadCloser) Close() error { + io.Copy(ioutil.Discard, c.stdout) + return c.cmd.Wait() +} + +// DataAsync gets a ReadCloser for the contents of a blob without reading it all. +// Calling the Close function on the result will discard all unread output. +func (b *Blob) DataAsync() (io.ReadCloser, error) { + cmd := exec.Command("git", "show", b.ID.String()) + cmd.Dir = b.repo.Path + cmd.Stderr = os.Stderr + + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, fmt.Errorf("StdoutPipe: %v", err) + } + + if err = cmd.Start(); err != nil { + return nil, fmt.Errorf("Start: %v", err) + } + + return cmdReadCloser{stdout: stdout, cmd: cmd}, nil +} diff --git a/vendor/code.gitea.io/git/command.go b/vendor/code.gitea.io/git/command.go new file mode 100644 index 0000000000000..8ca99fd6d3add --- /dev/null +++ b/vendor/code.gitea.io/git/command.go @@ -0,0 +1,134 @@ +// 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 git + +import ( + "bytes" + "context" + "fmt" + "io" + "os/exec" + "strings" + "time" +) + +var ( + // GlobalCommandArgs global command args for external package setting + GlobalCommandArgs []string + + // DefaultCommandExecutionTimeout default command execution timeout duration + DefaultCommandExecutionTimeout = 60 * time.Second +) + +// Command represents a command with its subcommands or arguments. +type Command struct { + name string + args []string +} + +func (c *Command) String() string { + if len(c.args) == 0 { + return c.name + } + return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " ")) +} + +// NewCommand creates and returns a new Git Command based on given command and arguments. +func NewCommand(args ...string) *Command { + return &Command{ + name: "git", + args: append(GlobalCommandArgs, args...), + } +} + +// AddArguments adds new argument(s) to the command. +func (c *Command) AddArguments(args ...string) *Command { + c.args = append(c.args, args...) + return c +} + +// RunInDirTimeoutPipeline executes the command in given directory with given timeout, +// it pipes stdout and stderr to given io.Writer. +func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error { + if timeout == -1 { + timeout = DefaultCommandExecutionTimeout + } + + if len(dir) == 0 { + log(c.String()) + } else { + log("%s: %v", dir, c) + } + + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + cmd := exec.CommandContext(ctx, c.name, c.args...) + cmd.Dir = dir + cmd.Stdout = stdout + cmd.Stderr = stderr + if err := cmd.Start(); err != nil { + return err + } + + if err := cmd.Wait(); err != nil { + return err + } + + return ctx.Err() +} + +// RunInDirTimeout executes the command in given directory with given timeout, +// and returns stdout in []byte and error (combined with stderr). +func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + if err := c.RunInDirTimeoutPipeline(timeout, dir, stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + + if stdout.Len() > 0 { + log("stdout:\n%s", stdout.Bytes()[:1024]) + } + return stdout.Bytes(), nil +} + +// RunInDirPipeline executes the command in given directory, +// it pipes stdout and stderr to given io.Writer. +func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { + return c.RunInDirTimeoutPipeline(-1, dir, stdout, stderr) +} + +// RunInDirBytes executes the command in given directory +// and returns stdout in []byte and error (combined with stderr). +func (c *Command) RunInDirBytes(dir string) ([]byte, error) { + return c.RunInDirTimeout(-1, dir) +} + +// RunInDir executes the command in given directory +// and returns stdout in string and error (combined with stderr). +func (c *Command) RunInDir(dir string) (string, error) { + stdout, err := c.RunInDirTimeout(-1, dir) + if err != nil { + return "", err + } + return string(stdout), nil +} + +// RunTimeout executes the command in defualt working directory with given timeout, +// and returns stdout in string and error (combined with stderr). +func (c *Command) RunTimeout(timeout time.Duration) (string, error) { + stdout, err := c.RunInDirTimeout(timeout, "") + if err != nil { + return "", err + } + return string(stdout), nil +} + +// Run executes the command in defualt working directory +// and returns stdout in string and error (combined with stderr). +func (c *Command) Run() (string, error) { + return c.RunTimeout(-1) +} diff --git a/vendor/code.gitea.io/git/commit.go b/vendor/code.gitea.io/git/commit.go new file mode 100644 index 0000000000000..299a2381b65b6 --- /dev/null +++ b/vendor/code.gitea.io/git/commit.go @@ -0,0 +1,276 @@ +// 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 git + +import ( + "bufio" + "bytes" + "container/list" + "fmt" + "net/http" + "strconv" + "strings" +) + +// Commit represents a git commit. +type Commit struct { + Tree + ID SHA1 // The ID of this commit object + Author *Signature + Committer *Signature + CommitMessage string + Signature *CommitGPGSignature + + parents []SHA1 // SHA1 strings + submoduleCache *ObjectCache +} + +// CommitGPGSignature represents a git commit signature part. +type CommitGPGSignature struct { + Signature string + Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data +} + +// similar to https://github.com/git/git/blob/3bc53220cb2dcf709f7a027a3f526befd021d858/commit.c#L1128 +func newGPGSignatureFromCommitline(data []byte, signatureStart int) (*CommitGPGSignature, error) { + sig := new(CommitGPGSignature) + signatureEnd := bytes.LastIndex(data, []byte("-----END PGP SIGNATURE-----")) + if signatureEnd == -1 { + return nil, fmt.Errorf("end of commit signature not found") + } + sig.Signature = strings.Replace(string(data[signatureStart:signatureEnd+27]), "\n ", "\n", -1) + sig.Payload = string(data[:signatureStart-8]) + string(data[signatureEnd+27:]) + return sig, nil +} + +// Message returns the commit message. Same as retrieving CommitMessage directly. +func (c *Commit) Message() string { + return c.CommitMessage +} + +// Summary returns first line of commit message. +func (c *Commit) Summary() string { + return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0] +} + +// ParentID returns oid of n-th parent (0-based index). +// It returns nil if no such parent exists. +func (c *Commit) ParentID(n int) (SHA1, error) { + if n >= len(c.parents) { + return SHA1{}, ErrNotExist{"", ""} + } + return c.parents[n], nil +} + +// Parent returns n-th parent (0-based index) of the commit. +func (c *Commit) Parent(n int) (*Commit, error) { + id, err := c.ParentID(n) + if err != nil { + return nil, err + } + parent, err := c.repo.getCommit(id) + if err != nil { + return nil, err + } + return parent, nil +} + +// ParentCount returns number of parents of the commit. +// 0 if this is the root commit, otherwise 1,2, etc. +func (c *Commit) ParentCount() int { + return len(c.parents) +} + +func isImageFile(data []byte) (string, bool) { + contentType := http.DetectContentType(data) + if strings.Index(contentType, "image/") != -1 { + return contentType, true + } + return contentType, false +} + +// IsImageFile is a file image type +func (c *Commit) IsImageFile(name string) bool { + blob, err := c.GetBlobByPath(name) + if err != nil { + return false + } + + dataRc, err := blob.DataAsync() + if err != nil { + return false + } + defer dataRc.Close() + buf := make([]byte, 1024) + n, _ := dataRc.Read(buf) + buf = buf[:n] + _, isImage := isImageFile(buf) + return isImage +} + +// GetCommitByPath return the commit of relative path object. +func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) { + return c.repo.getCommitByPathWithID(c.ID, relpath) +} + +// AddChanges marks local changes to be ready for commit. +func AddChanges(repoPath string, all bool, files ...string) error { + cmd := NewCommand("add") + if all { + cmd.AddArguments("--all") + } + _, err := cmd.AddArguments(files...).RunInDir(repoPath) + return err +} + +// CommitChangesOptions the options when a commit created +type CommitChangesOptions struct { + Committer *Signature + Author *Signature + Message string +} + +// CommitChanges commits local changes with given committer, author and message. +// If author is nil, it will be the same as committer. +func CommitChanges(repoPath string, opts CommitChangesOptions) error { + cmd := NewCommand() + if opts.Committer != nil { + cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email) + } + cmd.AddArguments("commit") + + if opts.Author == nil { + opts.Author = opts.Committer + } + if opts.Author != nil { + cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)) + } + cmd.AddArguments("-m", opts.Message) + + _, err := cmd.RunInDir(repoPath) + // No stderr but exit status 1 means nothing to commit. + if err != nil && err.Error() == "exit status 1" { + return nil + } + return err +} + +func commitsCount(repoPath, revision, relpath string) (int64, error) { + var cmd *Command + cmd = NewCommand("rev-list", "--count") + cmd.AddArguments(revision) + if len(relpath) > 0 { + cmd.AddArguments("--", relpath) + } + + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return 0, err + } + + return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) +} + +// CommitsCount returns number of total commits of until given revision. +func CommitsCount(repoPath, revision string) (int64, error) { + return commitsCount(repoPath, revision, "") +} + +// CommitsCount returns number of total commits of until current revision. +func (c *Commit) CommitsCount() (int64, error) { + return CommitsCount(c.repo.Path, c.ID.String()) +} + +// CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize +func (c *Commit) CommitsByRange(page int) (*list.List, error) { + return c.repo.commitsByRange(c.ID, page) +} + +// CommitsBefore returns all the commits before current revision +func (c *Commit) CommitsBefore() (*list.List, error) { + return c.repo.getCommitsBefore(c.ID) +} + +// CommitsBeforeLimit returns num commits before current revision +func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) { + return c.repo.getCommitsBeforeLimit(c.ID, num) +} + +// CommitsBeforeUntil returns the commits between commitID to current revision +func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) { + endCommit, err := c.repo.GetCommit(commitID) + if err != nil { + return nil, err + } + return c.repo.CommitsBetween(c, endCommit) +} + +// SearchCommits returns the commits match the keyword before current revision +func (c *Commit) SearchCommits(keyword string, all bool) (*list.List, error) { + return c.repo.searchCommits(c.ID, keyword, all) +} + +// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision +func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) { + return c.repo.getFilesChanged(pastCommit, c.ID.String()) +} + +// GetSubModules get all the sub modules of current revision git tree +func (c *Commit) GetSubModules() (*ObjectCache, error) { + if c.submoduleCache != nil { + return c.submoduleCache, nil + } + + entry, err := c.GetTreeEntryByPath(".gitmodules") + if err != nil { + if _, ok := err.(ErrNotExist); ok { + return nil, nil + } + return nil, err + } + rd, err := entry.Blob().Data() + if err != nil { + return nil, err + } + + scanner := bufio.NewScanner(rd) + c.submoduleCache = newObjectCache() + var ismodule bool + var path string + for scanner.Scan() { + if strings.HasPrefix(scanner.Text(), "[submodule") { + ismodule = true + continue + } + if ismodule { + fields := strings.Split(scanner.Text(), "=") + k := strings.TrimSpace(fields[0]) + if k == "path" { + path = strings.TrimSpace(fields[1]) + } else if k == "url" { + c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])}) + ismodule = false + } + } + } + + return c.submoduleCache, nil +} + +// GetSubModule get the sub module according entryname +func (c *Commit) GetSubModule(entryname string) (*SubModule, error) { + modules, err := c.GetSubModules() + if err != nil { + return nil, err + } + + if modules != nil { + module, has := modules.Get(entryname) + if has { + return module.(*SubModule), nil + } + } + return nil, nil +} diff --git a/vendor/code.gitea.io/git/commit_archive.go b/vendor/code.gitea.io/git/commit_archive.go new file mode 100644 index 0000000000000..e13825a96283b --- /dev/null +++ b/vendor/code.gitea.io/git/commit_archive.go @@ -0,0 +1,37 @@ +// 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 git + +import ( + "fmt" + "path/filepath" + "strings" +) + +// ArchiveType archive types +type ArchiveType int + +const ( + // ZIP zip archive type + ZIP ArchiveType = iota + 1 + // TARGZ tar gz archive type + TARGZ +) + +// CreateArchive create archive content to the target path +func (c *Commit) CreateArchive(target string, archiveType ArchiveType) error { + var format string + switch archiveType { + case ZIP: + format = "zip" + case TARGZ: + format = "tar.gz" + default: + return fmt.Errorf("unknown format: %v", archiveType) + } + + _, err := NewCommand("archive", "--prefix="+filepath.Base(strings.TrimSuffix(c.repo.Path, ".git"))+"/", "--format="+format, "-o", target, c.ID.String()).RunInDir(c.repo.Path) + return err +} diff --git a/vendor/code.gitea.io/git/commit_info.go b/vendor/code.gitea.io/git/commit_info.go new file mode 100644 index 0000000000000..6b42b57c90133 --- /dev/null +++ b/vendor/code.gitea.io/git/commit_info.go @@ -0,0 +1,319 @@ +// 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 git + +import ( + "bufio" + "context" + "fmt" + "os/exec" + "path" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // parameters for searching for commit infos. If the untargeted search has + // not found any entries in the past 5 commits, and 12 or fewer entries + // remain, then we'll just let the targeted-searching threads finish off, + // and stop the untargeted search to not interfere. + deferToTargetedSearchColdStreak = 5 + deferToTargetedSearchNumRemainingEntries = 12 +) + +// getCommitsInfoState shared state while getting commit info for entries +type getCommitsInfoState struct { + lock sync.Mutex + /* read-only fields, can be read without the mutex */ + // entries and entryPaths are read-only after initialization, so they can + // safely be read without the mutex + entries []*TreeEntry + // set of filepaths to get info for + entryPaths map[string]struct{} + treePath string + headCommit *Commit + + /* mutable fields, must hold mutex to read or write */ + // map from filepath to commit + commits map[string]*Commit + // set of filepaths that have been or are being searched for in a target search + targetedPaths map[string]struct{} +} + +func (state *getCommitsInfoState) numRemainingEntries() int { + state.lock.Lock() + defer state.lock.Unlock() + return len(state.entries) - len(state.commits) +} + +// getTargetEntryPath Returns the next path for a targeted-searching thread to +// search for, or returns the empty string if nothing left to search for +func (state *getCommitsInfoState) getTargetedEntryPath() string { + var targetedEntryPath string + state.lock.Lock() + defer state.lock.Unlock() + for _, entry := range state.entries { + entryPath := path.Join(state.treePath, entry.Name()) + if _, ok := state.commits[entryPath]; ok { + continue + } else if _, ok = state.targetedPaths[entryPath]; ok { + continue + } + targetedEntryPath = entryPath + state.targetedPaths[entryPath] = struct{}{} + break + } + return targetedEntryPath +} + +// repeatedly perform targeted searches for unpopulated entries +func targetedSearch(state *getCommitsInfoState, done chan error) { + for { + entryPath := state.getTargetedEntryPath() + if len(entryPath) == 0 { + done <- nil + return + } + command := NewCommand("rev-list", "-1", state.headCommit.ID.String(), "--", entryPath) + output, err := command.RunInDir(state.headCommit.repo.Path) + if err != nil { + done <- err + return + } + id, err := NewIDFromString(strings.TrimSpace(output)) + if err != nil { + done <- err + return + } + commit, err := state.headCommit.repo.getCommit(id) + if err != nil { + done <- err + return + } + state.update(entryPath, commit) + } +} + +func initGetCommitInfoState(entries Entries, headCommit *Commit, treePath string) *getCommitsInfoState { + entryPaths := make(map[string]struct{}, len(entries)) + for _, entry := range entries { + entryPaths[path.Join(treePath, entry.Name())] = struct{}{} + } + if treePath = path.Clean(treePath); treePath == "." { + treePath = "" + } + return &getCommitsInfoState{ + entries: entries, + entryPaths: entryPaths, + commits: make(map[string]*Commit, len(entries)), + targetedPaths: make(map[string]struct{}, len(entries)), + treePath: treePath, + headCommit: headCommit, + } +} + +// GetCommitsInfo gets information of all commits that are corresponding to these entries +func (tes Entries) GetCommitsInfo(commit *Commit, treePath string) ([][]interface{}, error) { + state := initGetCommitInfoState(tes, commit, treePath) + if err := getCommitsInfo(state); err != nil { + return nil, err + } + if len(state.commits) < len(state.entryPaths) { + return nil, fmt.Errorf("could not find commits for all entries") + } + + commitsInfo := make([][]interface{}, len(tes)) + for i, entry := range tes { + commit, ok := state.commits[path.Join(treePath, entry.Name())] + if !ok { + return nil, fmt.Errorf("could not find commit for %s", entry.Name()) + } + switch entry.Type { + case ObjectCommit: + subModuleURL := "" + if subModule, err := state.headCommit.GetSubModule(entry.Name()); err != nil { + return nil, err + } else if subModule != nil { + subModuleURL = subModule.URL + } + subModuleFile := NewSubModuleFile(commit, subModuleURL, entry.ID.String()) + commitsInfo[i] = []interface{}{entry, subModuleFile} + default: + commitsInfo[i] = []interface{}{entry, commit} + } + } + return commitsInfo, nil +} + +func (state *getCommitsInfoState) cleanEntryPath(rawEntryPath string) (string, error) { + if rawEntryPath[0] == '"' { + var err error + rawEntryPath, err = strconv.Unquote(rawEntryPath) + if err != nil { + return rawEntryPath, err + } + } + var entryNameStartIndex int + if len(state.treePath) > 0 { + entryNameStartIndex = len(state.treePath) + 1 + } + + if index := strings.IndexByte(rawEntryPath[entryNameStartIndex:], '/'); index >= 0 { + return rawEntryPath[:entryNameStartIndex+index], nil + } + return rawEntryPath, nil +} + +// update report that the given path was last modified by the given commit. +// Returns whether state.commits was updated +func (state *getCommitsInfoState) update(entryPath string, commit *Commit) bool { + if _, ok := state.entryPaths[entryPath]; !ok { + return false + } + + var updated bool + state.lock.Lock() + defer state.lock.Unlock() + if _, ok := state.commits[entryPath]; !ok { + state.commits[entryPath] = commit + updated = true + } + return updated +} + +const getCommitsInfoPretty = "--pretty=format:%H %ct %s" + +func getCommitsInfo(state *getCommitsInfoState) error { + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + defer cancel() + + args := []string{"log", state.headCommit.ID.String(), getCommitsInfoPretty, "--name-status", "-c"} + if len(state.treePath) > 0 { + args = append(args, "--", state.treePath) + } + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Dir = state.headCommit.repo.Path + + readCloser, err := cmd.StdoutPipe() + if err != nil { + return err + } + + if err := cmd.Start(); err != nil { + return err + } + // it's okay to ignore the error returned by cmd.Wait(); we expect the + // subprocess to sometimes have a non-zero exit status, since we may + // prematurely close stdout, resulting in a broken pipe. + defer cmd.Wait() + + numThreads := runtime.NumCPU() + done := make(chan error, numThreads) + for i := 0; i < numThreads; i++ { + go targetedSearch(state, done) + } + + scanner := bufio.NewScanner(readCloser) + err = state.processGitLogOutput(scanner) + + // it is important that we close stdout here; if we do not close + // stdout, the subprocess will keep running, and the deffered call + // cmd.Wait() may block for a long time. + if closeErr := readCloser.Close(); closeErr != nil && err == nil { + err = closeErr + } + + for i := 0; i < numThreads; i++ { + doneErr := <-done + if doneErr != nil && err == nil { + err = doneErr + } + } + return err +} + +func (state *getCommitsInfoState) processGitLogOutput(scanner *bufio.Scanner) error { + // keep a local cache of seen paths to avoid acquiring a lock for paths + // we've already seen + seenPaths := make(map[string]struct{}, len(state.entryPaths)) + // number of consecutive commits without any finds + coldStreak := 0 + var commit *Commit + var err error + for scanner.Scan() { + line := scanner.Text() + if len(line) == 0 { // in-between commits + numRemainingEntries := state.numRemainingEntries() + if numRemainingEntries == 0 { + break + } + if coldStreak >= deferToTargetedSearchColdStreak && + numRemainingEntries <= deferToTargetedSearchNumRemainingEntries { + // stop this untargeted search, and let the targeted-search threads + // finish the work + break + } + continue + } + if line[0] >= 'A' && line[0] <= 'X' { // a file was changed by the current commit + // look for the last tab, since for copies (C) and renames (R) two + // filenames are printed: src, then dest + tabIndex := strings.LastIndexByte(line, '\t') + if tabIndex < 1 { + return fmt.Errorf("misformatted line: %s", line) + } + entryPath, err := state.cleanEntryPath(line[tabIndex+1:]) + if err != nil { + return err + } + if _, ok := seenPaths[entryPath]; !ok { + if state.update(entryPath, commit) { + coldStreak = 0 + } + seenPaths[entryPath] = struct{}{} + } + continue + } + + // a new commit + commit, err = parseCommitInfo(line) + if err != nil { + return err + } + coldStreak++ + } + return scanner.Err() +} + +// parseCommitInfo parse a commit from a line of `git log` output. Expects the +// line to be formatted according to getCommitsInfoPretty. +func parseCommitInfo(line string) (*Commit, error) { + if len(line) < 43 { + return nil, fmt.Errorf("invalid git output: %s", line) + } + ref, err := NewIDFromString(line[:40]) + if err != nil { + return nil, err + } + spaceIndex := strings.IndexByte(line[41:], ' ') + if spaceIndex < 0 { + return nil, fmt.Errorf("invalid git output: %s", line) + } + unixSeconds, err := strconv.Atoi(line[41 : 41+spaceIndex]) + if err != nil { + return nil, err + } + message := line[spaceIndex+42:] + return &Commit{ + ID: ref, + CommitMessage: message, + Committer: &Signature{ + When: time.Unix(int64(unixSeconds), 0), + }, + }, nil +} diff --git a/vendor/code.gitea.io/git/doc.go b/vendor/code.gitea.io/git/doc.go new file mode 100644 index 0000000000000..1941d285507b1 --- /dev/null +++ b/vendor/code.gitea.io/git/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 git // import "code.gitea.io/git" diff --git a/vendor/code.gitea.io/git/error.go b/vendor/code.gitea.io/git/error.go new file mode 100644 index 0000000000000..1aae5a37a2891 --- /dev/null +++ b/vendor/code.gitea.io/git/error.go @@ -0,0 +1,66 @@ +// 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 git + +import ( + "fmt" + "time" +) + +// ErrExecTimeout error when exec timed out +type ErrExecTimeout struct { + Duration time.Duration +} + +// IsErrExecTimeout if some error is ErrExecTimeout +func IsErrExecTimeout(err error) bool { + _, ok := err.(ErrExecTimeout) + return ok +} + +func (err ErrExecTimeout) Error() string { + return fmt.Sprintf("execution is timeout [duration: %v]", err.Duration) +} + +// ErrNotExist commit not exist error +type ErrNotExist struct { + ID string + RelPath string +} + +// IsErrNotExist if some error is ErrNotExist +func IsErrNotExist(err error) bool { + _, ok := err.(ErrNotExist) + return ok +} + +func (err ErrNotExist) Error() string { + return fmt.Sprintf("object does not exist [id: %s, rel_path: %s]", err.ID, err.RelPath) +} + +// ErrBadLink entry.FollowLink error +type ErrBadLink struct { + Name string + Message string +} + +func (err ErrBadLink) Error() string { + return fmt.Sprintf("%s: %s", err.Name, err.Message) +} + +// ErrUnsupportedVersion error when required git version not matched +type ErrUnsupportedVersion struct { + Required string +} + +// IsErrUnsupportedVersion if some error is ErrUnsupportedVersion +func IsErrUnsupportedVersion(err error) bool { + _, ok := err.(ErrUnsupportedVersion) + return ok +} + +func (err ErrUnsupportedVersion) Error() string { + return fmt.Sprintf("Operation requires higher version [required: %s]", err.Required) +} diff --git a/vendor/code.gitea.io/git/git.go b/vendor/code.gitea.io/git/git.go new file mode 100644 index 0000000000000..150b80fb076b8 --- /dev/null +++ b/vendor/code.gitea.io/git/git.go @@ -0,0 +1,91 @@ +// Copyright 2015 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 git + +import ( + "fmt" + "strings" + "time" + + "github.com/mcuadros/go-version" +) + +// Version return this package's current version +func Version() string { + return "0.4.2" +} + +var ( + // Debug enables verbose logging on everything. + // This should be false in case Gogs starts in SSH mode. + Debug = false + // Prefix the log prefix + Prefix = "[git-module] " + // GitVersionRequired is the minimum Git version required + GitVersionRequired = "1.7.2" +) + +func log(format string, args ...interface{}) { + if !Debug { + return + } + + fmt.Print(Prefix) + if len(args) == 0 { + fmt.Println(format) + } else { + fmt.Printf(format+"\n", args...) + } +} + +var gitVersion string + +// BinVersion returns current Git version from shell. +func BinVersion() (string, error) { + if len(gitVersion) > 0 { + return gitVersion, nil + } + + stdout, err := NewCommand("version").Run() + if err != nil { + return "", err + } + + fields := strings.Fields(stdout) + if len(fields) < 3 { + return "", fmt.Errorf("not enough output: %s", stdout) + } + + // Handle special case on Windows. + i := strings.Index(fields[2], "windows") + if i >= 1 { + gitVersion = fields[2][:i-1] + return gitVersion, nil + } + + gitVersion = fields[2] + return gitVersion, nil +} + +func init() { + gitVersion, err := BinVersion() + if err != nil { + panic(fmt.Sprintf("Git version missing: %v", err)) + } + if version.Compare(gitVersion, GitVersionRequired, "<") { + panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired)) + } +} + +// Fsck verifies the connectivity and validity of the objects in the database +func Fsck(repoPath string, timeout time.Duration, args ...string) error { + // Make sure timeout makes sense. + if timeout <= 0 { + timeout = -1 + } + _, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) + return err +} diff --git a/vendor/code.gitea.io/git/hook.go b/vendor/code.gitea.io/git/hook.go new file mode 100644 index 0000000000000..afed623e6eacf --- /dev/null +++ b/vendor/code.gitea.io/git/hook.go @@ -0,0 +1,126 @@ +// 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 git + +import ( + "errors" + "io/ioutil" + "os" + "path" + "path/filepath" + "strings" + + "github.com/Unknwon/com" +) + +// hookNames is a list of Git server hooks' name that are supported. +var hookNames = []string{ + "pre-receive", + "update", + "post-receive", +} + +var ( + // ErrNotValidHook error when a git hook is not valid + ErrNotValidHook = errors.New("not a valid Git hook") +) + +// IsValidHookName returns true if given name is a valid Git hook. +func IsValidHookName(name string) bool { + for _, hn := range hookNames { + if hn == name { + return true + } + } + return false +} + +// Hook represents a Git hook. +type Hook struct { + name string + IsActive bool // Indicates whether repository has this hook. + Content string // Content of hook if it's active. + Sample string // Sample content from Git. + path string // Hook file path. +} + +// GetHook returns a Git hook by given name and repository. +func GetHook(repoPath, name string) (*Hook, error) { + if !IsValidHookName(name) { + return nil, ErrNotValidHook + } + h := &Hook{ + name: name, + path: path.Join(repoPath, "hooks", name+".d", name), + } + samplePath := filepath.Join(repoPath, "hooks", name+".sample") + if isFile(h.path) { + data, err := ioutil.ReadFile(h.path) + if err != nil { + return nil, err + } + h.IsActive = true + h.Content = string(data) + } else if isFile(samplePath) { + data, err := ioutil.ReadFile(samplePath) + if err != nil { + return nil, err + } + h.Sample = string(data) + } + return h, nil +} + +// Name return the name of the hook +func (h *Hook) Name() string { + return h.name +} + +// Update updates hook settings. +func (h *Hook) Update() error { + if len(strings.TrimSpace(h.Content)) == 0 { + if isExist(h.path) { + return os.Remove(h.path) + } + return nil + } + return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm) +} + +// ListHooks returns a list of Git hooks of given repository. +func ListHooks(repoPath string) (_ []*Hook, err error) { + if !isDir(path.Join(repoPath, "hooks")) { + return nil, errors.New("hooks path does not exist") + } + + hooks := make([]*Hook, len(hookNames)) + for i, name := range hookNames { + hooks[i], err = GetHook(repoPath, name) + if err != nil { + return nil, err + } + } + return hooks, nil +} + +const ( + // HookPathUpdate hook update path + HookPathUpdate = "hooks/update" +) + +// SetUpdateHook writes given content to update hook of the reposiotry. +func SetUpdateHook(repoPath, content string) (err error) { + log("Setting update hook: %s", repoPath) + hookPath := path.Join(repoPath, HookPathUpdate) + if com.IsExist(hookPath) { + err = os.Remove(hookPath) + } else { + err = os.MkdirAll(path.Dir(hookPath), os.ModePerm) + } + if err != nil { + return err + } + return ioutil.WriteFile(hookPath, []byte(content), 0777) +} diff --git a/vendor/code.gitea.io/git/parse.go b/vendor/code.gitea.io/git/parse.go new file mode 100644 index 0000000000000..5c964f16ee5f7 --- /dev/null +++ b/vendor/code.gitea.io/git/parse.go @@ -0,0 +1,81 @@ +// 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 git + +import ( + "bytes" + "fmt" + "strconv" +) + +// ParseTreeEntries parses the output of a `git ls-tree` command. +func ParseTreeEntries(data []byte) ([]*TreeEntry, error) { + return parseTreeEntries(data, nil) +} + +func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) { + entries := make([]*TreeEntry, 0, 10) + for pos := 0; pos < len(data); { + // expect line to be of the form " \t" + entry := new(TreeEntry) + entry.ptree = ptree + if pos+6 > len(data) { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + switch string(data[pos : pos+6]) { + case "100644": + entry.mode = EntryModeBlob + entry.Type = ObjectBlob + pos += 12 // skip over "100644 blob " + case "100755": + entry.mode = EntryModeExec + entry.Type = ObjectBlob + pos += 12 // skip over "100755 blob " + case "120000": + entry.mode = EntryModeSymlink + entry.Type = ObjectBlob + pos += 12 // skip over "120000 blob " + case "160000": + entry.mode = EntryModeCommit + entry.Type = ObjectCommit + pos += 14 // skip over "160000 object " + case "040000": + entry.mode = EntryModeTree + entry.Type = ObjectTree + pos += 12 // skip over "040000 tree " + default: + return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6])) + } + + if pos+40 > len(data) { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + id, err := NewIDFromString(string(data[pos : pos+40])) + if err != nil { + return nil, fmt.Errorf("Invalid ls-tree output: %v", err) + } + entry.ID = id + pos += 41 // skip over sha and trailing space + + end := pos + bytes.IndexByte(data[pos:], '\n') + if end < pos { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + + // In case entry name is surrounded by double quotes(it happens only in git-shell). + if data[pos] == '"' { + entry.name, err = strconv.Unquote(string(data[pos:end])) + if err != nil { + return nil, fmt.Errorf("Invalid ls-tree output: %v", err) + } + } else { + entry.name = string(data[pos:end]) + } + + pos = end + 1 + entries = append(entries, entry) + } + return entries, nil +} diff --git a/vendor/code.gitea.io/git/repo.go b/vendor/code.gitea.io/git/repo.go new file mode 100644 index 0000000000000..4306730920eb2 --- /dev/null +++ b/vendor/code.gitea.io/git/repo.go @@ -0,0 +1,287 @@ +// Copyright 2015 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 git + +import ( + "bytes" + "container/list" + "errors" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/Unknwon/com" +) + +// Repository represents a Git repository. +type Repository struct { + Path string + + commitCache *ObjectCache + tagCache *ObjectCache +} + +const prettyLogFormat = `--pretty=format:%H` + +func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) { + l := list.New() + if len(logs) == 0 { + return l, nil + } + + parts := bytes.Split(logs, []byte{'\n'}) + + for _, commitID := range parts { + commit, err := repo.GetCommit(string(commitID)) + if err != nil { + return nil, err + } + l.PushBack(commit) + } + + return l, nil +} + +// IsRepoURLAccessible checks if given repository URL is accessible. +func IsRepoURLAccessible(url string) bool { + _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run() + if err != nil { + return false + } + return true +} + +// InitRepository initializes a new Git repository. +func InitRepository(repoPath string, bare bool) error { + os.MkdirAll(repoPath, os.ModePerm) + + cmd := NewCommand("init") + if bare { + cmd.AddArguments("--bare") + } + _, err := cmd.RunInDir(repoPath) + return err +} + +// OpenRepository opens the repository at the given path. +func OpenRepository(repoPath string) (*Repository, error) { + repoPath, err := filepath.Abs(repoPath) + if err != nil { + return nil, err + } else if !isDir(repoPath) { + return nil, errors.New("no such file or directory") + } + + return &Repository{ + Path: repoPath, + commitCache: newObjectCache(), + tagCache: newObjectCache(), + }, nil +} + +// CloneRepoOptions options when clone a repository +type CloneRepoOptions struct { + Timeout time.Duration + Mirror bool + Bare bool + Quiet bool + Branch string +} + +// Clone clones original repository to target path. +func Clone(from, to string, opts CloneRepoOptions) (err error) { + toDir := path.Dir(to) + if err = os.MkdirAll(toDir, os.ModePerm); err != nil { + return err + } + + cmd := NewCommand("clone") + if opts.Mirror { + cmd.AddArguments("--mirror") + } + if opts.Bare { + cmd.AddArguments("--bare") + } + if opts.Quiet { + cmd.AddArguments("--quiet") + } + if len(opts.Branch) > 0 { + cmd.AddArguments("-b", opts.Branch) + } + cmd.AddArguments(from, to) + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + _, err = cmd.RunTimeout(opts.Timeout) + return err +} + +// PullRemoteOptions options when pull from remote +type PullRemoteOptions struct { + Timeout time.Duration + All bool + Rebase bool + Remote string + Branch string +} + +// Pull pulls changes from remotes. +func Pull(repoPath string, opts PullRemoteOptions) error { + cmd := NewCommand("pull") + if opts.Rebase { + cmd.AddArguments("--rebase") + } + if opts.All { + cmd.AddArguments("--all") + } else { + cmd.AddArguments(opts.Remote) + cmd.AddArguments(opts.Branch) + } + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) + return err +} + +// PushOptions options when push to remote +type PushOptions struct { + Remote string + Branch string + Force bool +} + +// Push pushs local commits to given remote branch. +func Push(repoPath string, opts PushOptions) error { + cmd := NewCommand("push") + if opts.Force { + cmd.AddArguments("-f") + } + cmd.AddArguments(opts.Remote, opts.Branch) + _, err := cmd.RunInDir(repoPath) + return err +} + +// CheckoutOptions options when heck out some branch +type CheckoutOptions struct { + Timeout time.Duration + Branch string + OldBranch string +} + +// Checkout checkouts a branch +func Checkout(repoPath string, opts CheckoutOptions) error { + cmd := NewCommand("checkout") + if len(opts.OldBranch) > 0 { + cmd.AddArguments("-b") + } + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + cmd.AddArguments(opts.Branch) + + if len(opts.OldBranch) > 0 { + cmd.AddArguments(opts.OldBranch) + } + + _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) + return err +} + +// ResetHEAD resets HEAD to given revision or head of branch. +func ResetHEAD(repoPath string, hard bool, revision string) error { + cmd := NewCommand("reset") + if hard { + cmd.AddArguments("--hard") + } + _, err := cmd.AddArguments(revision).RunInDir(repoPath) + return err +} + +// MoveFile moves a file to another file or directory. +func MoveFile(repoPath, oldTreeName, newTreeName string) error { + _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath) + return err +} + +// CountObject represents repository count objects report +type CountObject struct { + Count int64 + Size int64 + InPack int64 + Packs int64 + SizePack int64 + PrunePack int64 + Garbage int64 + SizeGarbage int64 +} + +const ( + statCount = "count: " + statSize = "size: " + statInpack = "in-pack: " + statPacks = "packs: " + statSizePack = "size-pack: " + statPrunePackage = "prune-package: " + statGarbage = "garbage: " + statSizeGarbage = "size-garbage: " +) + +// GetRepoSize returns disk consumption for repo in path +func GetRepoSize(repoPath string) (*CountObject, error) { + cmd := NewCommand("count-objects", "-v") + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return nil, err + } + + return parseSize(stdout), nil +} + +// parseSize parses the output from count-objects and return a CountObject +func parseSize(objects string) *CountObject { + repoSize := new(CountObject) + for _, line := range strings.Split(objects, "\n") { + switch { + case strings.HasPrefix(line, statCount): + repoSize.Count = com.StrTo(line[7:]).MustInt64() + case strings.HasPrefix(line, statSize): + repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024 + case strings.HasPrefix(line, statInpack): + repoSize.InPack = com.StrTo(line[9:]).MustInt64() + case strings.HasPrefix(line, statPacks): + repoSize.Packs = com.StrTo(line[7:]).MustInt64() + case strings.HasPrefix(line, statSizePack): + repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024 + case strings.HasPrefix(line, statPrunePackage): + repoSize.PrunePack = com.StrTo(line[16:]).MustInt64() + case strings.HasPrefix(line, statGarbage): + repoSize.Garbage = com.StrTo(line[9:]).MustInt64() + case strings.HasPrefix(line, statSizeGarbage): + repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024 + } + } + return repoSize +} + +// GetLatestCommitTime returns time for latest commit in repository (across all branches) +func GetLatestCommitTime(repoPath string) (time.Time, error) { + cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)") + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return time.Time{}, err + } + commitTime := strings.TrimSpace(stdout) + return time.Parse(GitTimeLayout, commitTime) +} diff --git a/vendor/code.gitea.io/git/repo_blame.go b/vendor/code.gitea.io/git/repo_blame.go new file mode 100644 index 0000000000000..80ec50e4723cf --- /dev/null +++ b/vendor/code.gitea.io/git/repo_blame.go @@ -0,0 +1,24 @@ +// 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 git + +import "fmt" + +// FileBlame return the Blame object of file +func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { + return NewCommand("blame", "--root", "--", file).RunInDirBytes(path) +} + +// LineBlame returns the latest commit at the given line +func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { + res, err := NewCommand("blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) + if err != nil { + return nil, err + } + if len(res) < 40 { + return nil, fmt.Errorf("invalid result of blame: %s", res) + } + return repo.GetCommit(string(res[:40])) +} diff --git a/vendor/code.gitea.io/git/repo_branch.go b/vendor/code.gitea.io/git/repo_branch.go new file mode 100644 index 0000000000000..3b50eece14a31 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_branch.go @@ -0,0 +1,123 @@ +// 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 git + +import ( + "fmt" + "strings" +) + +// BranchPrefix base dir of the branch information file store on git +const BranchPrefix = "refs/heads/" + +// IsReferenceExist returns true if given reference exists in the repository. +func IsReferenceExist(repoPath, name string) bool { + _, err := NewCommand("show-ref", "--verify", name).RunInDir(repoPath) + return err == nil +} + +// IsBranchExist returns true if given branch exists in the repository. +func IsBranchExist(repoPath, name string) bool { + return IsReferenceExist(repoPath, BranchPrefix+name) +} + +// IsBranchExist returns true if given branch exists in current repository. +func (repo *Repository) IsBranchExist(name string) bool { + return IsBranchExist(repo.Path, name) +} + +// Branch represents a Git branch. +type Branch struct { + Name string + Path string +} + +// GetHEADBranch returns corresponding branch of HEAD. +func (repo *Repository) GetHEADBranch() (*Branch, error) { + stdout, err := NewCommand("symbolic-ref", "HEAD").RunInDir(repo.Path) + if err != nil { + return nil, err + } + stdout = strings.TrimSpace(stdout) + + if !strings.HasPrefix(stdout, BranchPrefix) { + return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) + } + + return &Branch{ + Name: stdout[len(BranchPrefix):], + Path: stdout, + }, nil +} + +// SetDefaultBranch sets default branch of repository. +func (repo *Repository) SetDefaultBranch(name string) error { + _, err := NewCommand("symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) + return err +} + +// GetBranches returns all branches of the repository. +func (repo *Repository) GetBranches() ([]string, error) { + stdout, err := NewCommand("for-each-ref", "--format=%(refname)", BranchPrefix).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + refs := strings.Split(stdout, "\n") + branches := make([]string, len(refs)-1) + for i, ref := range refs[:len(refs)-1] { + branches[i] = strings.TrimPrefix(ref, BranchPrefix) + } + return branches, nil +} + +// DeleteBranchOptions Option(s) for delete branch +type DeleteBranchOptions struct { + Force bool +} + +// DeleteBranch delete a branch by name on repository. +func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { + cmd := NewCommand("branch") + + if opts.Force { + cmd.AddArguments("-D") + } else { + cmd.AddArguments("-d") + } + + cmd.AddArguments(name) + _, err := cmd.RunInDir(repo.Path) + + return err +} + +// CreateBranch create a new branch +func (repo *Repository) CreateBranch(branch, newBranch string) error { + cmd := NewCommand("branch") + cmd.AddArguments(branch, newBranch) + + _, err := cmd.RunInDir(repo.Path) + + return err +} + +// AddRemote adds a new remote to repository. +func (repo *Repository) AddRemote(name, url string, fetch bool) error { + cmd := NewCommand("remote", "add") + if fetch { + cmd.AddArguments("-f") + } + cmd.AddArguments(name, url) + + _, err := cmd.RunInDir(repo.Path) + return err +} + +// RemoveRemote removes a remote from repository. +func (repo *Repository) RemoveRemote(name string) error { + _, err := NewCommand("remote", "remove", name).RunInDir(repo.Path) + return err +} diff --git a/vendor/code.gitea.io/git/repo_commit.go b/vendor/code.gitea.io/git/repo_commit.go new file mode 100644 index 0000000000000..1acdfffb34738 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_commit.go @@ -0,0 +1,352 @@ +// 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 git + +import ( + "bytes" + "container/list" + "strconv" + "strings" + + "github.com/mcuadros/go-version" +) + +// GetRefCommitID returns the last commit ID string of given reference (branch or tag). +func (repo *Repository) GetRefCommitID(name string) (string, error) { + stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path) + if err != nil { + if strings.Contains(err.Error(), "not a valid ref") { + return "", ErrNotExist{name, ""} + } + return "", err + } + return strings.Split(stdout, " ")[0], nil +} + +// GetBranchCommitID returns last commit ID string of given branch. +func (repo *Repository) GetBranchCommitID(name string) (string, error) { + return repo.GetRefCommitID(BranchPrefix + name) +} + +// GetTagCommitID returns last commit ID string of given tag. +func (repo *Repository) GetTagCommitID(name string) (string, error) { + return repo.GetRefCommitID(TagPrefix + name) +} + +// parseCommitData parses commit information from the (uncompressed) raw +// data from the commit object. +// \n\n separate headers from message +func parseCommitData(data []byte) (*Commit, error) { + commit := new(Commit) + commit.parents = make([]SHA1, 0, 1) + // we now have the contents of the commit object. Let's investigate... + nextline := 0 +l: + for { + eol := bytes.IndexByte(data[nextline:], '\n') + switch { + case eol > 0: + line := data[nextline : nextline+eol] + spacepos := bytes.IndexByte(line, ' ') + reftype := line[:spacepos] + switch string(reftype) { + case "tree", "object": + id, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + commit.Tree.ID = id + case "parent": + // A commit can have one or more parents + oid, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + commit.parents = append(commit.parents, oid) + case "author", "tagger": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + commit.Author = sig + case "committer": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + commit.Committer = sig + case "gpgsig": + sig, err := newGPGSignatureFromCommitline(data, nextline+spacepos+1) + if err != nil { + return nil, err + } + commit.Signature = sig + } + nextline += eol + 1 + case eol == 0: + commit.CommitMessage = string(data[nextline+1:]) + break l + default: + break l + } + } + return commit, nil +} + +func (repo *Repository) getCommit(id SHA1) (*Commit, error) { + c, ok := repo.commitCache.Get(id.String()) + if ok { + log("Hit cache: %s", id) + return c.(*Commit), nil + } + + data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) + if err != nil { + if strings.Contains(err.Error(), "fatal: Not a valid object name") { + return nil, ErrNotExist{id.String(), ""} + } + return nil, err + } + + commit, err := parseCommitData(data) + if err != nil { + return nil, err + } + commit.repo = repo + commit.ID = id + + repo.commitCache.Set(id.String(), commit) + return commit, nil +} + +// GetCommit returns commit object of by ID string. +func (repo *Repository) GetCommit(commitID string) (*Commit, error) { + if len(commitID) != 40 { + var err error + commitID, err = NewCommand("rev-parse", commitID).RunInDir(repo.Path) + if err != nil { + return nil, err + } + } + id, err := NewIDFromString(commitID) + if err != nil { + return nil, err + } + + return repo.getCommit(id) +} + +// GetBranchCommit returns the last commit of given branch. +func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { + commitID, err := repo.GetBranchCommitID(name) + if err != nil { + return nil, err + } + return repo.GetCommit(commitID) +} + +// GetTagCommit get the commit of the specific tag via name +func (repo *Repository) GetTagCommit(name string) (*Commit, error) { + commitID, err := repo.GetTagCommitID(name) + if err != nil { + return nil, err + } + return repo.GetCommit(commitID) +} + +func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) { + // File name starts with ':' must be escaped. + if relpath[0] == ':' { + relpath = `\` + relpath + } + + stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + id, err = NewIDFromString(stdout) + if err != nil { + return nil, err + } + + return repo.getCommit(id) +} + +// GetCommitByPath returns the last commit of relative path. +func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { + stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + commits, err := repo.parsePrettyFormatLogToList(stdout) + if err != nil { + return nil, err + } + return commits.Front().Value.(*Commit), nil +} + +// CommitsRangeSize the default commits range size +var CommitsRangeSize = 50 + +func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) { + stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize), + "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +func (repo *Repository) searchCommits(id SHA1, keyword string, all bool) (*list.List, error) { + cmd := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, prettyLogFormat) + if all { + cmd.AddArguments("--all") + } + stdout, err := cmd.RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) { + stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return strings.Split(string(stdout), "\n"), nil +} + +// FileCommitsCount return the number of files at a revison +func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) { + return commitsCount(repo.Path, revision, file) +} + +// CommitsByFileAndRange return the commits accroding revison file and the page +func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) { + stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50), + "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +// FilesCountBetween return the number of files changed between two commits +func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { + stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) + if err != nil { + return 0, err + } + return len(strings.Split(stdout, "\n")) - 1, nil +} + +// CommitsBetween returns a list that contains commits between [last, before). +func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { + stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) +} + +// CommitsBetweenIDs return commits between twoe commits +func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) { + lastCommit, err := repo.GetCommit(last) + if err != nil { + return nil, err + } + beforeCommit, err := repo.GetCommit(before) + if err != nil { + return nil, err + } + return repo.CommitsBetween(lastCommit, beforeCommit) +} + +// CommitsCountBetween return numbers of commits between two commits +func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) { + return commitsCount(repo.Path, start+"..."+end, "") +} + +// commitsBefore the limit is depth, not total number of returned commits. +func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) { + cmd := NewCommand("log") + if limit > 0 { + cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String()) + } else { + cmd.AddArguments(prettyLogFormat, id.String()) + } + + stdout, err := cmd.RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) + if err != nil { + return nil, err + } + + commits := list.New() + for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() { + commit := logEntry.Value.(*Commit) + branches, err := repo.getBranches(commit, 2) + if err != nil { + return nil, err + } + + if len(branches) > 1 { + break + } + + commits.PushBack(commit) + } + + return commits, nil +} + +func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) { + return repo.commitsBefore(id, 0) +} + +func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) { + return repo.commitsBefore(id, num) +} + +func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { + if version.Compare(gitVersion, "2.7.0", ">=") { + stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + branches := strings.Fields(stdout) + return branches, nil + } + + stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + refs := strings.Split(stdout, "\n") + + var max int + if len(refs) > limit { + max = limit + } else { + max = len(refs) - 1 + } + + branches := make([]string, max) + for i, ref := range refs[:max] { + parts := strings.Fields(ref) + + branches[i] = parts[len(parts)-1] + } + return branches, nil +} diff --git a/vendor/code.gitea.io/git/repo_hook.go b/vendor/code.gitea.io/git/repo_hook.go new file mode 100644 index 0000000000000..49f4d09fb685b --- /dev/null +++ b/vendor/code.gitea.io/git/repo_hook.go @@ -0,0 +1,15 @@ +// 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 git + +// GetHook get one hook accroding the name on a repository +func (repo *Repository) GetHook(name string) (*Hook, error) { + return GetHook(repo.Path, name) +} + +// Hooks get all the hooks on the repository +func (repo *Repository) Hooks() ([]*Hook, error) { + return ListHooks(repo.Path) +} diff --git a/vendor/code.gitea.io/git/repo_object.go b/vendor/code.gitea.io/git/repo_object.go new file mode 100644 index 0000000000000..3be8400d22210 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_object.go @@ -0,0 +1,19 @@ +// 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 git + +// ObjectType git object type +type ObjectType string + +const ( + // ObjectCommit commit object type + ObjectCommit ObjectType = "commit" + // ObjectTree tree object type + ObjectTree ObjectType = "tree" + // ObjectBlob blob object type + ObjectBlob ObjectType = "blob" + // ObjectTag tag object type + ObjectTag ObjectType = "tag" +) diff --git a/vendor/code.gitea.io/git/repo_pull.go b/vendor/code.gitea.io/git/repo_pull.go new file mode 100644 index 0000000000000..c6d97a6fd167d --- /dev/null +++ b/vendor/code.gitea.io/git/repo_pull.go @@ -0,0 +1,89 @@ +// 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 git + +import ( + "bytes" + "container/list" + "fmt" + "io" + "strconv" + "strings" + "time" +) + +// PullRequestInfo represents needed information for a pull request. +type PullRequestInfo struct { + MergeBase string + Commits *list.List + NumFiles int +} + +// GetMergeBase checks and returns merge base of two branches. +func (repo *Repository) GetMergeBase(base, head string) (string, error) { + stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path) + return strings.TrimSpace(stdout), err +} + +// GetPullRequestInfo generates and returns pull request information +// between base and head branches of repositories. +func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) { + var remoteBranch string + + // We don't need a temporary remote for same repository. + if repo.Path != basePath { + // Add a temporary remote + tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) + if err = repo.AddRemote(tmpRemote, basePath, true); err != nil { + return nil, fmt.Errorf("AddRemote: %v", err) + } + defer repo.RemoveRemote(tmpRemote) + + remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch + } else { + remoteBranch = baseBranch + } + + prInfo := new(PullRequestInfo) + prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch) + if err != nil { + return nil, fmt.Errorf("GetMergeBase: %v", err) + } + + logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs) + if err != nil { + return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err) + } + + // Count number of changed files. + stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path) + if err != nil { + return nil, err + } + prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1 + + return prInfo, nil +} + +// GetPatch generates and returns patch data between given revisions. +func (repo *Repository) GetPatch(base, head string) ([]byte, error) { + return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path) +} + +// GetFormatPatch generates and returns format-patch data between given revisions. +func (repo *Repository) GetFormatPatch(base, head string) (io.Reader, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + + if err := NewCommand("format-patch", "--binary", "--stdout", base+"..."+head). + RunInDirPipeline(repo.Path, stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + return stdout, nil +} diff --git a/vendor/code.gitea.io/git/repo_tag.go b/vendor/code.gitea.io/git/repo_tag.go new file mode 100644 index 0000000000000..11f1f3da73af9 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_tag.go @@ -0,0 +1,157 @@ +// 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 git + +import ( + "strings" + + "github.com/mcuadros/go-version" +) + +// TagPrefix tags prefix path on the repository +const TagPrefix = "refs/tags/" + +// IsTagExist returns true if given tag exists in the repository. +func IsTagExist(repoPath, name string) bool { + return IsReferenceExist(repoPath, TagPrefix+name) +} + +// IsTagExist returns true if given tag exists in the repository. +func (repo *Repository) IsTagExist(name string) bool { + return IsTagExist(repo.Path, name) +} + +// CreateTag create one tag in the repository +func (repo *Repository) CreateTag(name, revision string) error { + _, err := NewCommand("tag", name, revision).RunInDir(repo.Path) + return err +} + +func (repo *Repository) getTag(id SHA1) (*Tag, error) { + t, ok := repo.tagCache.Get(id.String()) + if ok { + log("Hit cache: %s", id) + return t.(*Tag), nil + } + + // Get tag type + tp, err := NewCommand("cat-file", "-t", id.String()).RunInDir(repo.Path) + if err != nil { + return nil, err + } + tp = strings.TrimSpace(tp) + + // Tag is a commit. + if ObjectType(tp) == ObjectCommit { + tag := &Tag{ + ID: id, + Object: id, + Type: string(ObjectCommit), + repo: repo, + } + + repo.tagCache.Set(id.String(), tag) + return tag, nil + } + + // Tag with message. + data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + tag, err := parseTagData(data) + if err != nil { + return nil, err + } + + tag.ID = id + tag.repo = repo + + repo.tagCache.Set(id.String(), tag) + return tag, nil +} + +// GetTag returns a Git tag by given name. +func (repo *Repository) GetTag(name string) (*Tag, error) { + stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + id, err := NewIDFromString(strings.Split(stdout, " ")[0]) + if err != nil { + return nil, err + } + + tag, err := repo.getTag(id) + if err != nil { + return nil, err + } + tag.Name = name + return tag, nil +} + +// GetTagInfos returns all tag infos of the repository. +func (repo *Repository) GetTagInfos() ([]*Tag, error) { + // TODO this a slow implementation, makes one git command per tag + stdout, err := NewCommand("tag").RunInDir(repo.Path) + if err != nil { + return nil, err + } + + tagNames := strings.Split(stdout, "\n") + var tags []*Tag + for _, tagName := range tagNames { + tagName = strings.TrimSpace(tagName) + if len(tagName) == 0 { + continue + } + commitID, err := NewCommand("rev-parse", tagName).RunInDir(repo.Path) + if err != nil { + return nil, err + } + commit, err := repo.GetCommit(commitID) + if err != nil { + return nil, err + } + tags = append(tags, &Tag{ + Name: tagName, + Message: commit.Message(), + Object: commit.ID, + Tagger: commit.Author, + }) + } + sortTagsByTime(tags) + return tags, nil +} + +// GetTags returns all tags of the repository. +func (repo *Repository) GetTags() ([]string, error) { + cmd := NewCommand("tag", "-l") + if version.Compare(gitVersion, "2.0.0", ">=") { + cmd.AddArguments("--sort=-v:refname") + } + + stdout, err := cmd.RunInDir(repo.Path) + if err != nil { + return nil, err + } + + tags := strings.Split(stdout, "\n") + tags = tags[:len(tags)-1] + + if version.Compare(gitVersion, "2.0.0", "<") { + version.Sort(tags) + + // Reverse order + for i := 0; i < len(tags)/2; i++ { + j := len(tags) - i - 1 + tags[i], tags[j] = tags[j], tags[i] + } + } + + return tags, nil +} diff --git a/vendor/code.gitea.io/git/repo_tree.go b/vendor/code.gitea.io/git/repo_tree.go new file mode 100644 index 0000000000000..6e3843f7e5389 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_tree.go @@ -0,0 +1,26 @@ +// 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 git + +func (repo *Repository) getTree(id SHA1) (*Tree, error) { + treePath := filepathFromSHA1(repo.Path, id.String()) + if isFile(treePath) { + _, err := NewCommand("ls-tree", id.String()).RunInDir(repo.Path) + if err != nil { + return nil, ErrNotExist{id.String(), ""} + } + } + + return NewTree(repo, id), nil +} + +// GetTree find the tree object in the repository. +func (repo *Repository) GetTree(idStr string) (*Tree, error) { + id, err := NewIDFromString(idStr) + if err != nil { + return nil, err + } + return repo.getTree(id) +} diff --git a/vendor/code.gitea.io/git/sha1.go b/vendor/code.gitea.io/git/sha1.go new file mode 100644 index 0000000000000..6c9d53949dff9 --- /dev/null +++ b/vendor/code.gitea.io/git/sha1.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 git + +import ( + "bytes" + "encoding/hex" + "fmt" + "strings" +) + +// EmptySHA defines empty git SHA +const EmptySHA = "0000000000000000000000000000000000000000" + +// SHA1 a git commit name +type SHA1 [20]byte + +// Equal returns true if s has the same SHA1 as caller. +// Support 40-length-string, []byte, SHA1. +func (id SHA1) Equal(s2 interface{}) bool { + switch v := s2.(type) { + case string: + if len(v) != 40 { + return false + } + return v == id.String() + case []byte: + return bytes.Equal(v, id[:]) + case SHA1: + return v == id + default: + return false + } +} + +// String returns string (hex) representation of the Oid. +func (id SHA1) String() string { + return hex.EncodeToString(id[:]) +} + +// MustID always creates a new SHA1 from a [20]byte array with no validation of input. +func MustID(b []byte) SHA1 { + var id SHA1 + copy(id[:], b) + return id +} + +// NewID creates a new SHA1 from a [20]byte array. +func NewID(b []byte) (SHA1, error) { + if len(b) != 20 { + return SHA1{}, fmt.Errorf("Length must be 20: %v", b) + } + return MustID(b), nil +} + +// MustIDFromString always creates a new sha from a ID with no validation of input. +func MustIDFromString(s string) SHA1 { + b, _ := hex.DecodeString(s) + return MustID(b) +} + +// NewIDFromString creates a new SHA1 from a ID string of length 40. +func NewIDFromString(s string) (SHA1, error) { + var id SHA1 + s = strings.TrimSpace(s) + if len(s) != 40 { + return id, fmt.Errorf("Length must be 40: %s", s) + } + b, err := hex.DecodeString(s) + if err != nil { + return id, err + } + return NewID(b) +} diff --git a/vendor/code.gitea.io/git/signature.go b/vendor/code.gitea.io/git/signature.go new file mode 100644 index 0000000000000..e6ab247fd73fa --- /dev/null +++ b/vendor/code.gitea.io/git/signature.go @@ -0,0 +1,58 @@ +// 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 git + +import ( + "bytes" + "strconv" + "time" +) + +// Signature represents the Author or Committer information. +type Signature struct { + Email string + Name string + When time.Time +} + +const ( + // GitTimeLayout is the (default) time layout used by git. + GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700" +) + +// Helper to get a signature from the commit line, which looks like these: +// author Patrick Gundlach 1378823654 +0200 +// author Patrick Gundlach Thu, 07 Apr 2005 22:13:13 +0200 +// but without the "author " at the beginning (this method should) +// be used for author and committer. +// +// FIXME: include timezone for timestamp! +func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { + sig := new(Signature) + emailStart := bytes.IndexByte(line, '<') + sig.Name = string(line[:emailStart-1]) + emailEnd := bytes.IndexByte(line, '>') + sig.Email = string(line[emailStart+1 : emailEnd]) + + // Check date format. + if len(line) > emailEnd+2 { + firstChar := line[emailEnd+2] + if firstChar >= 48 && firstChar <= 57 { + timestop := bytes.IndexByte(line[emailEnd+2:], ' ') + timestring := string(line[emailEnd+2 : emailEnd+2+timestop]) + seconds, _ := strconv.ParseInt(timestring, 10, 64) + sig.When = time.Unix(seconds, 0) + } else { + sig.When, err = time.Parse(GitTimeLayout, string(line[emailEnd+2:])) + if err != nil { + return nil, err + } + } + } else { + // Fall back to unix 0 time + sig.When = time.Unix(0, 0) + } + return sig, nil +} diff --git a/vendor/code.gitea.io/git/submodule.go b/vendor/code.gitea.io/git/submodule.go new file mode 100644 index 0000000000000..a0fe7b4a5691c --- /dev/null +++ b/vendor/code.gitea.io/git/submodule.go @@ -0,0 +1,79 @@ +// 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 git + +import "strings" + +// SubModule submodule is a reference on git repository +type SubModule struct { + Name string + URL string +} + +// SubModuleFile represents a file with submodule type. +type SubModuleFile struct { + *Commit + + refURL string + refID string +} + +// NewSubModuleFile create a new submodule file +func NewSubModuleFile(c *Commit, refURL, refID string) *SubModuleFile { + return &SubModuleFile{ + Commit: c, + refURL: refURL, + refID: refID, + } +} + +// RefURL guesses and returns reference URL. +func (sf *SubModuleFile) RefURL(urlPrefix string, parentPath string) string { + if sf.refURL == "" { + return "" + } + + url := strings.TrimSuffix(sf.refURL, ".git") + + // git://xxx/user/repo + if strings.HasPrefix(url, "git://") { + return "http://" + strings.TrimPrefix(url, "git://") + } + + // http[s]://xxx/user/repo + if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { + return url + } + + // Relative url prefix check (according to git submodule documentation) + if strings.HasPrefix(url, "./") || strings.HasPrefix(url, "../") { + // ...construct and return correct submodule url here... + idx := strings.Index(parentPath, "/src/") + if idx == -1 { + return url + } + return strings.TrimSuffix(urlPrefix, "/") + parentPath[:idx] + "/" + url + } + + // sysuser@xxx:user/repo + i := strings.Index(url, "@") + j := strings.LastIndex(url, ":") + + // Only process when i < j because git+ssh://git@git.forwardbias.in/npploader.git + if i > -1 && j > -1 && i < j { + // fix problem with reverse proxy works only with local server + if strings.Contains(urlPrefix, url[i+1:j]) { + return urlPrefix + url[j+1:] + } + return "http://" + url[i+1:j] + "/" + url[j+1:] + } + + return url +} + +// RefID returns reference ID. +func (sf *SubModuleFile) RefID() string { + return sf.refID +} diff --git a/vendor/code.gitea.io/git/tag.go b/vendor/code.gitea.io/git/tag.go new file mode 100644 index 0000000000000..500fd274914c4 --- /dev/null +++ b/vendor/code.gitea.io/git/tag.go @@ -0,0 +1,89 @@ +// 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 git + +import ( + "bytes" + "sort" +) + +// Tag represents a Git tag. +type Tag struct { + Name string + ID SHA1 + repo *Repository + Object SHA1 // The id of this commit object + Type string + Tagger *Signature + Message string +} + +// Commit return the commit of the tag reference +func (tag *Tag) Commit() (*Commit, error) { + return tag.repo.getCommit(tag.Object) +} + +// Parse commit information from the (uncompressed) raw +// data from the commit object. +// \n\n separate headers from message +func parseTagData(data []byte) (*Tag, error) { + tag := new(Tag) + // we now have the contents of the commit object. Let's investigate... + nextline := 0 +l: + for { + eol := bytes.IndexByte(data[nextline:], '\n') + switch { + case eol > 0: + line := data[nextline : nextline+eol] + spacepos := bytes.IndexByte(line, ' ') + reftype := line[:spacepos] + switch string(reftype) { + case "object": + id, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + tag.Object = id + case "type": + // A commit can have one or more parents + tag.Type = string(line[spacepos+1:]) + case "tagger": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + tag.Tagger = sig + } + nextline += eol + 1 + case eol == 0: + tag.Message = string(data[nextline+1:]) + break l + default: + break l + } + } + return tag, nil +} + +type tagSorter []*Tag + +func (ts tagSorter) Len() int { + return len([]*Tag(ts)) +} + +func (ts tagSorter) Less(i, j int) bool { + return []*Tag(ts)[i].Tagger.When.After([]*Tag(ts)[j].Tagger.When) +} + +func (ts tagSorter) Swap(i, j int) { + []*Tag(ts)[i], []*Tag(ts)[j] = []*Tag(ts)[j], []*Tag(ts)[i] +} + +// sortTagsByTime +func sortTagsByTime(tags []*Tag) { + sorter := tagSorter(tags) + sort.Sort(sorter) +} diff --git a/vendor/code.gitea.io/git/tree.go b/vendor/code.gitea.io/git/tree.go new file mode 100644 index 0000000000000..4654dac30ea7c --- /dev/null +++ b/vendor/code.gitea.io/git/tree.go @@ -0,0 +1,72 @@ +// 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 git + +import ( + "strings" +) + +// Tree represents a flat directory listing. +type Tree struct { + ID SHA1 + repo *Repository + + // parent tree + ptree *Tree + + entries Entries + entriesParsed bool +} + +// NewTree create a new tree according the repository and commit id +func NewTree(repo *Repository, id SHA1) *Tree { + return &Tree{ + ID: id, + repo: repo, + } +} + +// SubTree get a sub tree by the sub dir path +func (t *Tree) SubTree(rpath string) (*Tree, error) { + if len(rpath) == 0 { + return t, nil + } + + paths := strings.Split(rpath, "/") + var ( + err error + g = t + p = t + te *TreeEntry + ) + for _, name := range paths { + te, err = p.GetTreeEntryByPath(name) + if err != nil { + return nil, err + } + + g, err = t.repo.getTree(te.ID) + if err != nil { + return nil, err + } + g.ptree = p + p = g + } + return g, nil +} + +// ListEntries returns all entries of current tree. +func (t *Tree) ListEntries() (Entries, error) { + if t.entriesParsed { + return t.entries, nil + } + + stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path) + if err != nil { + return nil, err + } + t.entries, err = parseTreeEntries(stdout, t) + return t.entries, err +} diff --git a/vendor/code.gitea.io/git/tree_blob.go b/vendor/code.gitea.io/git/tree_blob.go new file mode 100644 index 0000000000000..b3d205d8e10e9 --- /dev/null +++ b/vendor/code.gitea.io/git/tree_blob.go @@ -0,0 +1,59 @@ +// 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 git + +import ( + "path" + "strings" +) + +// GetTreeEntryByPath get the tree entries accroding the sub dir +func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { + if len(relpath) == 0 { + return &TreeEntry{ + ID: t.ID, + Type: ObjectTree, + mode: EntryModeTree, + }, nil + } + + relpath = path.Clean(relpath) + parts := strings.Split(relpath, "/") + var err error + tree := t + for i, name := range parts { + if i == len(parts)-1 { + entries, err := tree.ListEntries() + if err != nil { + return nil, err + } + for _, v := range entries { + if v.name == name { + return v, nil + } + } + } else { + tree, err = tree.SubTree(name) + if err != nil { + return nil, err + } + } + } + return nil, ErrNotExist{"", relpath} +} + +// GetBlobByPath get the blob object accroding the path +func (t *Tree) GetBlobByPath(relpath string) (*Blob, error) { + entry, err := t.GetTreeEntryByPath(relpath) + if err != nil { + return nil, err + } + + if !entry.IsDir() { + return entry.Blob(), nil + } + + return nil, ErrNotExist{"", relpath} +} diff --git a/vendor/code.gitea.io/git/tree_entry.go b/vendor/code.gitea.io/git/tree_entry.go new file mode 100644 index 0000000000000..6201eef8fd5bd --- /dev/null +++ b/vendor/code.gitea.io/git/tree_entry.go @@ -0,0 +1,200 @@ +// 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 git + +import ( + "io" + "sort" + "strconv" + "strings" +) + +// EntryMode the type of the object in the git tree +type EntryMode int + +// There are only a few file modes in Git. They look like unix file modes, but they can only be +// one of these. +const ( + // EntryModeBlob + EntryModeBlob EntryMode = 0100644 + // EntryModeExec + EntryModeExec EntryMode = 0100755 + // EntryModeSymlink + EntryModeSymlink EntryMode = 0120000 + // EntryModeCommit + EntryModeCommit EntryMode = 0160000 + // EntryModeTree + EntryModeTree EntryMode = 0040000 +) + +// TreeEntry the leaf in the git tree +type TreeEntry struct { + ID SHA1 + Type ObjectType + + mode EntryMode + name string + + ptree *Tree + + commited bool + + size int64 + sized bool +} + +// Name returns the name of the entry +func (te *TreeEntry) Name() string { + return te.name +} + +// Size returns the size of the entry +func (te *TreeEntry) Size() int64 { + if te.IsDir() { + return 0 + } else if te.sized { + return te.size + } + + stdout, err := NewCommand("cat-file", "-s", te.ID.String()).RunInDir(te.ptree.repo.Path) + if err != nil { + return 0 + } + + te.sized = true + te.size, _ = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) + return te.size +} + +// IsSubModule if the entry is a sub module +func (te *TreeEntry) IsSubModule() bool { + return te.mode == EntryModeCommit +} + +// IsDir if the entry is a sub dir +func (te *TreeEntry) IsDir() bool { + return te.mode == EntryModeTree +} + +// IsLink if the entry is a symlink +func (te *TreeEntry) IsLink() bool { + return te.mode == EntryModeSymlink +} + +// Blob retrun the blob object the entry +func (te *TreeEntry) Blob() *Blob { + return &Blob{ + repo: te.ptree.repo, + TreeEntry: te, + } +} + +// FollowLink returns the entry pointed to by a symlink +func (te *TreeEntry) FollowLink() (*TreeEntry, error) { + if !te.IsLink() { + return nil, ErrBadLink{te.Name(), "not a symlink"} + } + + // read the link + r, err := te.Blob().Data() + if err != nil { + return nil, err + } + buf := make([]byte, te.Size()) + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, err + } + + lnk := string(buf) + t := te.ptree + + // traverse up directories + for ; t != nil && strings.HasPrefix(lnk, "../"); lnk = lnk[3:] { + t = t.ptree + } + + if t == nil { + return nil, ErrBadLink{te.Name(), "points outside of repo"} + } + + target, err := t.GetTreeEntryByPath(lnk) + if err != nil { + if IsErrNotExist(err) { + return nil, ErrBadLink{te.Name(), "broken link"} + } + return nil, err + } + return target, nil +} + +// GetSubJumpablePathName return the full path of subdirectory jumpable ( contains only one directory ) +func (te *TreeEntry) GetSubJumpablePathName() string { + if te.IsSubModule() || !te.IsDir() { + return "" + } + tree, err := te.ptree.SubTree(te.name) + if err != nil { + return te.name + } + entries, _ := tree.ListEntries() + if len(entries) == 1 && entries[0].IsDir() { + name := entries[0].GetSubJumpablePathName() + if name != "" { + return te.name + "/" + name + } + } + return te.name +} + +// Entries a list of entry +type Entries []*TreeEntry + +type customSortableEntries struct { + Comparer func(s1, s2 string) bool + Entries +} + +var sorter = []func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool{ + func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { + return (t1.IsDir() || t1.IsSubModule()) && !t2.IsDir() && !t2.IsSubModule() + }, + func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { + return cmp(t1.name, t2.name) + }, +} + +func (ctes customSortableEntries) Len() int { return len(ctes.Entries) } + +func (ctes customSortableEntries) Swap(i, j int) { + ctes.Entries[i], ctes.Entries[j] = ctes.Entries[j], ctes.Entries[i] +} + +func (ctes customSortableEntries) Less(i, j int) bool { + t1, t2 := ctes.Entries[i], ctes.Entries[j] + var k int + for k = 0; k < len(sorter)-1; k++ { + s := sorter[k] + switch { + case s(t1, t2, ctes.Comparer): + return true + case s(t2, t1, ctes.Comparer): + return false + } + } + return sorter[k](t1, t2, ctes.Comparer) +} + +// Sort sort the list of entry +func (tes Entries) Sort() { + sort.Sort(customSortableEntries{func(s1, s2 string) bool { + return s1 < s2 + }, tes}) +} + +// CustomSort customizable string comparing sort entry list +func (tes Entries) CustomSort(cmp func(s1, s2 string) bool) { + sort.Sort(customSortableEntries{cmp, tes}) +} diff --git a/vendor/code.gitea.io/git/utils.go b/vendor/code.gitea.io/git/utils.go new file mode 100644 index 0000000000000..8f010321cf836 --- /dev/null +++ b/vendor/code.gitea.io/git/utils.go @@ -0,0 +1,96 @@ +// 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 git + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" +) + +// ObjectCache provides thread-safe cache opeations. +type ObjectCache struct { + lock sync.RWMutex + cache map[string]interface{} +} + +func newObjectCache() *ObjectCache { + return &ObjectCache{ + cache: make(map[string]interface{}, 10), + } +} + +// Set add obj to cache +func (oc *ObjectCache) Set(id string, obj interface{}) { + oc.lock.Lock() + defer oc.lock.Unlock() + + oc.cache[id] = obj +} + +// Get get cached obj by id +func (oc *ObjectCache) Get(id string) (interface{}, bool) { + oc.lock.RLock() + defer oc.lock.RUnlock() + + obj, has := oc.cache[id] + return obj, has +} + +// isDir returns true if given path is a directory, +// or returns false when it's a file or does not exist. +func isDir(dir string) bool { + f, e := os.Stat(dir) + if e != nil { + return false + } + return f.IsDir() +} + +// isFile returns true if given path is a file, +// or returns false when it's a directory or does not exist. +func isFile(filePath string) bool { + f, e := os.Stat(filePath) + if e != nil { + return false + } + return !f.IsDir() +} + +// isExist checks whether a file or directory exists. +// It returns false when the file or directory does not exist. +func isExist(path string) bool { + _, err := os.Stat(path) + return err == nil || os.IsExist(err) +} + +func concatenateError(err error, stderr string) error { + if len(stderr) == 0 { + return err + } + return fmt.Errorf("%v - %s", err, stderr) +} + +// If the object is stored in its own file (i.e not in a pack file), +// this function returns the full path to the object file. +// It does not test if the file exists. +func filepathFromSHA1(rootdir, sha1 string) string { + return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:]) +} + +// RefEndName return the end name of a ref name +func RefEndName(refStr string) string { + if strings.HasPrefix(refStr, BranchPrefix) { + return refStr[len(BranchPrefix):] + } + + if strings.HasPrefix(refStr, TagPrefix) { + return refStr[len(TagPrefix):] + } + + return refStr +} diff --git a/vendor/code.gitea.io/sdk/LICENSE b/vendor/code.gitea.io/sdk/LICENSE new file mode 100644 index 0000000000000..10aeba46bcfc9 --- /dev/null +++ b/vendor/code.gitea.io/sdk/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 0000000000000..4071b6f187fcc --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_org.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" +) + +// 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 0000000000000..cf565ffa38b1c --- /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 0000000000000..089ff2964495b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_user.go @@ -0,0 +1,82 @@ +// 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" +) + +// CreateUserOption create user options +type CreateUserOption struct { + SourceID int64 `json:"source_id"` + LoginName string `json:"login_name"` + // required: true + Username string `json:"username" binding:"Required;AlphaDashDot;MaxSize(35)"` + FullName string `json:"full_name" binding:"MaxSize(100)"` + // required: true + // swagger:strfmt email + Email string `json:"email" binding:"Required;Email;MaxSize(254)"` + // required: true + Password string `json:"password" binding:"Required;MaxSize(255)"` + 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" binding:"MaxSize(100)"` + // required: true + // swagger:strfmt email + Email string `json:"email" binding:"Required;Email;MaxSize(254)"` + Password string `json:"password" binding:"MaxSize(255)"` + Website string `json:"website" binding:"MaxSize(50)"` + Location string `json:"location" binding:"MaxSize(50)"` + 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 create one user with options +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) +} 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 0000000000000..8c527de735c39 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/attachment.go @@ -0,0 +1,92 @@ +// 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 +// swagger:model +type Attachment struct { + ID int64 `json:"id"` + Name string `json:"name"` + Size int64 `json:"size"` + DownloadCount int64 `json:"download_count"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + UUID string `json:"uuid"` + DownloadURL string `json:"browser_download_url"` +} + +// ListReleaseAttachments list release's attachments +func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*Attachment, error) { + attachments := make([]*Attachment, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), + 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 +} + +// 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 +} + +// EditAttachmentOptions options for editing attachments +// swagger:model +type EditAttachmentOptions struct { + Name string `json:"name"` +} 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 0000000000000..6bd327db4623c --- /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 0000000000000..57222498ef54c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/fork.go @@ -0,0 +1,39 @@ +// 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" +) + +// ListForks list a repository's forks +func (c *Client) ListForks(user, repo string) ([]*Repository, error) { + forks := make([]*Repository, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/forks", user, repo), + nil, nil, &forks) + return forks, err +} + +// 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) + err = c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/forks", user, repo), + jsonHeader, bytes.NewReader(body), &fork) + return fork, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/gitea.go b/vendor/code.gitea.io/sdk/gitea/gitea.go new file mode 100644 index 0000000000000..374a3faa9604c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/gitea.go @@ -0,0 +1,104 @@ +// 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 ( + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + "strings" +) + +// Version return the library version +func Version() string { + return "0.12.3" +} + +// Client represents a Gogs API client. +type Client struct { + url string + accessToken string + client *http.Client +} + +// NewClient initializes and returns a API client. +func NewClient(url, token string) *Client { + return &Client{ + url: strings.TrimSuffix(url, "/"), + accessToken: token, + client: &http.Client{}, + } +} + +// SetHTTPClient replaces default http.Client with user given one. +func (c *Client) SetHTTPClient(client *http.Client) { + c.client = client +} + +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 + } + req.Header.Set("Authorization", "token "+c.accessToken) + 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 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 { + return nil, err + } + 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/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go new file mode 100644 index 0000000000000..f346381679848 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/hook.go @@ -0,0 +1,531 @@ +// 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" + "errors" + "fmt" + "strings" + "time" +) + +var ( + // ErrInvalidReceiveHook FIXME + ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") +) + +// 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"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` +} + +// HookList represents a list of API hook. +type HookList []*Hook + +// ListOrgHooks list all the hooks of one organization +func (c *Client) ListOrgHooks(org string) (HookList, error) { + hooks := make([]*Hook, 0, 10) + return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks", org), nil, nil, &hooks) +} + +// ListRepoHooks list all the hooks of one repository +func (c *Client) ListRepoHooks(user, repo string) (HookList, error) { + hooks := make([]*Hook, 0, 10) + return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), 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 { + // required: true + // enum: gitea,gogs,slack,discord + Type string `json:"type" binding:"Required"` + // required: true + Config map[string]string `json:"config" binding:"Required"` + Events []string `json:"events"` + // default: false + 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"` + 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("/org/%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 +} + +// Payloader payload is some part of one hook +type Payloader interface { + SetSecret(string) + JSONPayload() ([]byte, error) +} + +// PayloadUser represents the author or committer of a commit +type PayloadUser struct { + // Full name of the commit author + Name string `json:"name"` + // swagger:strfmt email + 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"` + // swagger:strfmt date-time + Timestamp time.Time `json:"timestamp"` +} + +// 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"` +} + +var ( + _ Payloader = &CreatePayload{} + _ Payloader = &DeletePayload{} + _ Payloader = &ForkPayload{} + _ Payloader = &PushPayload{} + _ Payloader = &IssuePayload{} + _ Payloader = &IssueCommentPayload{} + _ Payloader = &PullRequestPayload{} + _ Payloader = &RepositoryPayload{} + _ Payloader = &ReleasePayload{} +) + +// _________ __ +// \_ ___ \_______ ____ _____ _/ |_ ____ +// / \ \/\_ __ \_/ __ \\__ \\ __\/ __ \ +// \ \____| | \/\ ___/ / __ \| | \ ___/ +// \______ /|__| \___ >____ /__| \___ > +// \/ \/ \/ \/ + +// CreatePayload FIXME +type CreatePayload struct { + Secret string `json:"secret"` + Sha string `json:"sha"` + Ref string `json:"ref"` + RefType string `json:"ref_type"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret FIXME +func (p *CreatePayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload return payload information +func (p *CreatePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ParseCreateHook parses create event hook content. +func ParseCreateHook(raw []byte) (*CreatePayload, error) { + hook := new(CreatePayload) + if err := json.Unmarshal(raw, hook); err != nil { + return nil, err + } + + // it is possible the JSON was parsed, however, + // was not from Gogs (maybe was from Bitbucket) + // So we'll check to be sure certain key fields + // were populated + switch { + case hook.Repo == nil: + return nil, ErrInvalidReceiveHook + case len(hook.Ref) == 0: + return nil, ErrInvalidReceiveHook + } + return hook, nil +} + +// ________ .__ __ +// \______ \ ____ | | _____/ |_ ____ +// | | \_/ __ \| | _/ __ \ __\/ __ \ +// | ` \ ___/| |_\ ___/| | \ ___/ +// /_______ /\___ >____/\___ >__| \___ > +// \/ \/ \/ \/ + +// PusherType define the type to push +type PusherType string + +// describe all the PusherTypes +const ( + PusherTypeUser PusherType = "user" +) + +// DeletePayload represents delete payload +type DeletePayload struct { + Ref string `json:"ref"` + RefType string `json:"ref_type"` + PusherType PusherType `json:"pusher_type"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *DeletePayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *DeletePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ___________ __ +// \_ _____/__________| | __ +// | __)/ _ \_ __ \ |/ / +// | \( <_> ) | \/ < +// \___ / \____/|__| |__|_ \ +// \/ \/ + +// ForkPayload represents fork payload +type ForkPayload struct { + Forkee *Repository `json:"forkee"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *ForkPayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *ForkPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// HookIssueCommentAction defines hook issue comment action +type HookIssueCommentAction string + +// all issue comment actions +const ( + HookIssueCommentCreated HookIssueCommentAction = "created" + HookIssueCommentEdited HookIssueCommentAction = "edited" + HookIssueCommentDeleted HookIssueCommentAction = "deleted" +) + +// IssueCommentPayload represents a payload information of issue comment event. +type IssueCommentPayload struct { + Action HookIssueCommentAction `json:"action"` + Issue *Issue `json:"issue"` + Comment *Comment `json:"comment"` + Changes *ChangesPayload `json:"changes,omitempty"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *IssueCommentPayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *IssueCommentPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// __________ .__ +// \______ \ ____ | | ____ _____ ______ ____ +// | _// __ \| | _/ __ \\__ \ / ___// __ \ +// | | \ ___/| |_\ ___/ / __ \_\___ \\ ___/ +// |____|_ /\___ >____/\___ >____ /____ >\___ > +// \/ \/ \/ \/ \/ \/ + +// HookReleaseAction defines hook release action type +type HookReleaseAction string + +// all release actions +const ( + HookReleasePublished HookReleaseAction = "published" + HookReleaseUpdated HookReleaseAction = "updated" + HookReleaseDeleted HookReleaseAction = "deleted" +) + +// ReleasePayload represents a payload information of release event. +type ReleasePayload struct { + Action HookReleaseAction `json:"action"` + Release *Release `json:"release"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *ReleasePayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *ReleasePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// __________ .__ +// \______ \__ __ _____| |__ +// | ___/ | \/ ___/ | \ +// | | | | /\___ \| Y \ +// |____| |____//____ >___| / +// \/ \/ + +// PushPayload represents a payload information of push event. +type PushPayload struct { + Secret string `json:"secret"` + Ref string `json:"ref"` + Before string `json:"before"` + After string `json:"after"` + CompareURL string `json:"compare_url"` + Commits []*PayloadCommit `json:"commits"` + Repo *Repository `json:"repository"` + Pusher *User `json:"pusher"` + Sender *User `json:"sender"` +} + +// SetSecret FIXME +func (p *PushPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload FIXME +func (p *PushPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ParsePushHook parses push event hook content. +func ParsePushHook(raw []byte) (*PushPayload, error) { + hook := new(PushPayload) + if err := json.Unmarshal(raw, hook); err != nil { + return nil, err + } + + switch { + case hook.Repo == nil: + return nil, ErrInvalidReceiveHook + case len(hook.Ref) == 0: + return nil, ErrInvalidReceiveHook + } + return hook, nil +} + +// Branch returns branch name from a payload +func (p *PushPayload) Branch() string { + return strings.Replace(p.Ref, "refs/heads/", "", -1) +} + +// .___ +// | | ______ ________ __ ____ +// | |/ ___// ___/ | \_/ __ \ +// | |\___ \ \___ \| | /\ ___/ +// |___/____ >____ >____/ \___ > +// \/ \/ \/ + +// HookIssueAction FIXME +type HookIssueAction string + +const ( + // HookIssueOpened opened + HookIssueOpened HookIssueAction = "opened" + // HookIssueClosed closed + HookIssueClosed HookIssueAction = "closed" + // HookIssueReOpened reopened + HookIssueReOpened HookIssueAction = "reopened" + // HookIssueEdited edited + HookIssueEdited HookIssueAction = "edited" + // HookIssueAssigned assigned + HookIssueAssigned HookIssueAction = "assigned" + // HookIssueUnassigned unassigned + HookIssueUnassigned HookIssueAction = "unassigned" + // HookIssueLabelUpdated label_updated + HookIssueLabelUpdated HookIssueAction = "label_updated" + // HookIssueLabelCleared label_cleared + HookIssueLabelCleared HookIssueAction = "label_cleared" + // HookIssueSynchronized synchronized + HookIssueSynchronized HookIssueAction = "synchronized" + // HookIssueMilestoned is an issue action for when a milestone is set on an issue. + HookIssueMilestoned HookIssueAction = "milestoned" + // HookIssueDemilestoned is an issue action for when a milestone is cleared on an issue. + HookIssueDemilestoned HookIssueAction = "demilestoned" +) + +// IssuePayload represents the payload information that is sent along with an issue event. +type IssuePayload struct { + Secret string `json:"secret"` + Action HookIssueAction `json:"action"` + Index int64 `json:"number"` + Changes *ChangesPayload `json:"changes,omitempty"` + Issue *Issue `json:"issue"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret modifies the secret of the IssuePayload. +func (p *IssuePayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload encodes the IssuePayload to JSON, with an indentation of two spaces. +func (p *IssuePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ChangesFromPayload FIXME +type ChangesFromPayload struct { + From string `json:"from"` +} + +// ChangesPayload FIXME +type ChangesPayload struct { + Title *ChangesFromPayload `json:"title,omitempty"` + Body *ChangesFromPayload `json:"body,omitempty"` +} + +// __________ .__ .__ __________ __ +// \______ \__ __| | | | \______ \ ____ ________ __ ____ _______/ |_ +// | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\ +// | | | | / |_| |__ | | \ ___< <_| | | /\ ___/ \___ \ | | +// |____| |____/|____/____/ |____|_ /\___ >__ |____/ \___ >____ > |__| +// \/ \/ |__| \/ \/ + +// PullRequestPayload represents a payload information of pull request event. +type PullRequestPayload struct { + Secret string `json:"secret"` + Action HookIssueAction `json:"action"` + Index int64 `json:"number"` + Changes *ChangesPayload `json:"changes,omitempty"` + PullRequest *PullRequest `json:"pull_request"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret modifies the secret of the PullRequestPayload. +func (p *PullRequestPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload FIXME +func (p *PullRequestPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +//__________ .__ __ +//\______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. +// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | +// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ | +// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| +// \/ \/|__| \/ \/ + +// HookRepoAction an action that happens to a repo +type HookRepoAction string + +const ( + // HookRepoCreated created + HookRepoCreated HookRepoAction = "created" + // HookRepoDeleted deleted + HookRepoDeleted HookRepoAction = "deleted" +) + +// RepositoryPayload payload for repository webhooks +type RepositoryPayload struct { + Secret string `json:"secret"` + Action HookRepoAction `json:"action"` + Repository *Repository `json:"repository"` + Organization *User `json:"organization"` + Sender *User `json:"sender"` +} + +// SetSecret set the payload's secret +func (p *RepositoryPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload JSON representation of the payload +func (p *RepositoryPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} 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 0000000000000..fee7cd6f9fca2 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue.go @@ -0,0 +1,154 @@ +// 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" + "time" +) + +// StateType issue state type +type StateType string + +const ( + // StateOpen pr is opend + StateOpen StateType = "open" + // StateClosed pr is closed + StateClosed StateType = "closed" +) + +// PullRequestMeta PR info if an issue is a PR +type PullRequestMeta struct { + HasMerged bool `json:"merged"` + Merged *time.Time `json:"merged_at"` +} + +// Issue represents an issue in a repository +// swagger:model +type Issue 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"` + // Whether the issue is open or closed + // + // type: string + // enum: open,closed + State StateType `json:"state"` + Comments int `json:"comments"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + // swagger:strfmt date-time + Closed *time.Time `json:"closed_at"` + // swagger:strfmt date-time + Deadline *time.Time `json:"due_date"` + + PullRequest *PullRequestMeta `json:"pull_request"` +} + +// ListIssueOption list issue options +type ListIssueOption struct { + Page int + State string +} + +// ListIssues returns all issues assigned the authenticated user +func (c *Client) ListIssues(opt ListIssueOption) ([]*Issue, error) { + issues := make([]*Issue, 0, 10) + return issues, c.getParsedResponse("GET", fmt.Sprintf("/issues?page=%d", opt.Page), nil, nil, &issues) +} + +// ListUserIssues returns all issues assigned to the authenticated user +func (c *Client) ListUserIssues(opt ListIssueOption) ([]*Issue, error) { + issues := make([]*Issue, 0, 10) + return issues, c.getParsedResponse("GET", fmt.Sprintf("/user/issues?page=%d", opt.Page), nil, nil, &issues) +} + +// ListRepoIssues returns all issues for a given repository +func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) { + issues := make([]*Issue, 0, 10) + return issues, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues?page=%d", owner, repo, opt.Page), nil, nil, &issues) +} + +// GetIssue returns a single issue for a given repository +func (c *Client) GetIssue(owner, repo string, index int64) (*Issue, error) { + issue := new(Issue) + return issue, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue) +} + +// CreateIssueOption options to create one issue +type CreateIssueOption struct { + // required:true + Title string `json:"title" binding:"Required"` + Body string `json:"body"` + // username of assignee + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + // swagger:strfmt date-time + 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 *string `json:"state"` + // swagger:strfmt date-time + 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) +} + +// EditDeadlineOption options for creating a deadline +type EditDeadlineOption struct { + // required:true + // swagger:strfmt date-time + Deadline *time.Time `json:"due_date"` +} + +// IssueDeadline represents an issue deadline +// swagger:model +type IssueDeadline struct { + // swagger:strfmt date-time + Deadline *time.Time `json:"due_date"` +} 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 0000000000000..2c8127c609734 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_comment.go @@ -0,0 +1,76 @@ +// 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" + "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"` + Body string `json:"body"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` +} + +// ListIssueComments list comments on an issue. +func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, error) { + comments := make([]*Comment, 0, 10) + return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments) +} + +// ListRepoIssueComments list comments for a given repo. +func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) { + comments := make([]*Comment, 0, 10) + return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments) +} + +// CreateIssueCommentOption options for creating a comment on an issue +type CreateIssueCommentOption struct { + // required:true + Body string `json:"body" binding:"Required"` +} + +// 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 { + // required: true + Body string `json:"body" binding:"Required"` +} + +// EditIssueComment edits an issue comment. +func (c *Client) EditIssueComment(owner, repo string, index, 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/%d/comments/%d", owner, repo, index, commentID), jsonHeader, bytes.NewReader(body), comment) +} + +// DeleteIssueComment deletes an issue comment. +func (c *Client) DeleteIssueComment(owner, repo string, index, commentID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, 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 0000000000000..47d1b8221e98b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_label.go @@ -0,0 +1,122 @@ +// 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 +// swagger:model +type Label struct { + ID int64 `json:"id"` + Name string `json:"name"` + // example: 00aabb + Color string `json:"color"` + URL string `json:"url"` +} + +// ListRepoLabels list labels of one repository +func (c *Client) ListRepoLabels(owner, repo string) ([]*Label, error) { + labels := make([]*Label, 0, 10) + return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), nil, nil, &labels) +} + +// 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 { + // required:true + Name string `json:"name" binding:"Required"` + // required:true + // example: #00aabb + Color string `json:"color" binding:"Required;Size(7)"` +} + +// CreateLabel create one label of repository +func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { + 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"` +} + +// 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 +} + +// IssueLabelsOption a collection of labels +type IssueLabelsOption struct { + // list of label IDs + Labels []int64 `json:"labels"` +} + +// GetIssueLabels get labels of one issue via issue id +func (c *Client) GetIssueLabels(owner, repo string, index int64) ([]*Label, error) { + labels := make([]*Label, 0, 5) + return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil, &labels) +} + +// 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 0000000000000..775a6a9117510 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -0,0 +1,80 @@ +// 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" + "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"` + // swagger:strfmt date-time + Closed *time.Time `json:"closed_at"` + // swagger:strfmt date-time + Deadline *time.Time `json:"due_on"` +} + +// ListRepoMilestones list all the milestones of one repository +func (c *Client) ListRepoMilestones(owner, repo string) ([]*Milestone, error) { + milestones := make([]*Milestone, 0, 10) + return milestones, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), nil, nil, &milestones) +} + +// 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"` + // swagger:strfmt date-time + 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) + return milestone, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) +} + +// 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_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go new file mode 100644 index 0000000000000..7f4b64cbb3f99 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go @@ -0,0 +1,68 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created"` + // Time in seconds + Time int64 `json:"time"` + UserID int64 `json:"user_id"` + IssueID int64 `json:"issue_id"` +} + +// TrackedTimes represent a list of tracked times +type TrackedTimes []*TrackedTime + +// GetUserTrackedTimes list tracked times of a user +func (c *Client) GetUserTrackedTimes(owner, repo, user string) (TrackedTimes, error) { + times := make(TrackedTimes, 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) (TrackedTimes, error) { + times := make(TrackedTimes, 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() (TrackedTimes, error) { + times := make(TrackedTimes, 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 + // required: true + Time int64 `json:"time" binding:"Required"` +} + +// 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) +} + +// ListTrackedTimes get tracked times of one issue via issue id +func (c *Client) ListTrackedTimes(owner, repo string, index int64) (TrackedTimes, error) { + times := make(TrackedTimes, 0, 5) + return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil, ×) +} diff --git a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go new file mode 100644 index 0000000000000..356636a3a2519 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go @@ -0,0 +1,65 @@ +// 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 ( + "time" +) + +// LFSLock represent a lock +// for use with the locks API. +type LFSLock struct { + ID string `json:"id"` + Path string `json:"path"` + LockedAt time.Time `json:"locked_at"` + Owner *LFSLockOwner `json:"owner"` +} + +// LFSLockOwner represent a lock owner +// for use with the locks API. +type LFSLockOwner struct { + Name string `json:"name"` +} + +// LFSLockRequest contains the path of the lock to create +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock +type LFSLockRequest struct { + Path string `json:"path"` +} + +// LFSLockResponse represent a lock created +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock +type LFSLockResponse struct { + Lock *LFSLock `json:"lock"` +} + +// LFSLockList represent a list of lock requested +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks +type LFSLockList struct { + Locks []*LFSLock `json:"locks"` + Next string `json:"next_cursor,omitempty"` +} + +// LFSLockListVerify represent a list of lock verification requested +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks-for-verification +type LFSLockListVerify struct { + Ours []*LFSLock `json:"ours"` + Theirs []*LFSLock `json:"theirs"` + Next string `json:"next_cursor,omitempty"` +} + +// LFSLockError contains information on the error that occurs +type LFSLockError struct { + Message string `json:"message"` + Lock *LFSLock `json:"lock,omitempty"` + Documentation string `json:"documentation_url,omitempty"` + RequestID string `json:"request_id,omitempty"` +} + +// LFSLockDeleteRequest contains params of a delete request +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#delete-lock +type LFSLockDeleteRequest struct { + Force bool `json:"force"` +} diff --git a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go new file mode 100644 index 0000000000000..3735047b7f886 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go @@ -0,0 +1,52 @@ +// 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 + +// SearchResults results of a successful search +type SearchResults struct { + OK bool `json:"ok"` + Data []*Repository `json:"data"` +} + +// SearchError error of a failed search +type SearchError struct { + OK bool `json:"ok"` + Error string `json:"error"` +} + +// MarkdownOption markdown options +type MarkdownOption struct { + // Text markdown to render + // + // in: body + Text string + // Mode to render + // + // in: body + Mode string + // Context to render + // + // in: body + Context string + // Is it a wiki page ? + // + // in: body + Wiki bool +} + +// MarkdownRender is a rendered markdown document +// swagger:response MarkdownRender +type MarkdownRender string + +// ServerVersion wraps the version of the server +type ServerVersion struct { + Version string `json:"version"` +} + +// ServerVersion returns the version of the server +func (c *Client) ServerVersion() (string, error) { + v := ServerVersion{} + return v.Version, c.getParsedResponse("GET", "/api/v1/version", nil, nil, &v) +} 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 0000000000000..19238d1028453 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org.go @@ -0,0 +1,68 @@ +// 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" +) + +// 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"` +} + +// ListMyOrgs list all of current user's organizations +func (c *Client) ListMyOrgs() ([]*Organization, error) { + orgs := make([]*Organization, 0, 5) + return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs) +} + +// ListUserOrgs list all of some user's organizations +func (c *Client) ListUserOrgs(user string) ([]*Organization, error) { + orgs := make([]*Organization, 0, 5) + return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs) +} + +// 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 { + // required: true + UserName string `json:"username" binding:"Required"` + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` +} + +// 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"` +} + +// 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 +} 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 0000000000000..9bb95af3e2624 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_member.go @@ -0,0 +1,26 @@ +// 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" +) + +// AddOrgMembershipOption add user to organization options +type AddOrgMembershipOption struct { + Role string `json:"role" binding:"Required"` +} + +// AddOrgMembership add some one to an organization's member +func (c *Client) AddOrgMembership(org, user string, opt AddOrgMembershipOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PUT", fmt.Sprintf("/orgs/%s/membership/%s", org, user), jsonHeader, bytes.NewReader(body)) + return err +} 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 0000000000000..2fc6796d43ff9 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_team.go @@ -0,0 +1,32 @@ +// 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 + +// Team represents a team in an organization +type Team struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + // enum: none,read,write,admin,owner + Permission string `json:"permission"` +} + +// CreateTeamOption options for creating a team +type CreateTeamOption struct { + // required: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` + Description string `json:"description" binding:"MaxSize(255)"` + // enum: read,write,admin + Permission string `json:"permission"` +} + +// EditTeamOption options for editing a team +type EditTeamOption struct { + // required: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` + Description string `json:"description" binding:"MaxSize(255)"` + // enum: read,write,admin + Permission string `json:"permission"` +} 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 0000000000000..6fcdd1d41b7e4 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -0,0 +1,151 @@ +// 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" + "time" +) + +// 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"` + // swagger:strfmt date-time + 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"` + + // swagger:strfmt date-time + Deadline *time.Time `json:"due_date"` + + // swagger:strfmt date-time + Created *time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated *time.Time `json:"updated_at"` + // swagger:strfmt date-time + Closed *time.Time `json:"closed_at"` +} + +// 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"` +} + +// ListPullRequestsOptions options for listing pull requests +type ListPullRequestsOptions struct { + Page int `json:"page"` + State string `json:"state"` +} + +// ListRepoPullRequests list PRs of one repository +func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + prs := make([]*PullRequest, 0, 10) + return prs, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), jsonHeader, bytes.NewReader(body), &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" binding:"Required"` + Base string `json:"base" binding:"Required"` + Title string `json:"title" binding:"Required"` + Body string `json:"body"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + // swagger:strfmt date-time + 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"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + State *string `json:"state"` + // swagger:strfmt date-time + 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/issues/%d", owner, repo, index), + jsonHeader, bytes.NewReader(body), pr) +} + +// MergePullRequest merge a PR to repository by PR id +func (c *Client) MergePullRequest(owner, repo string, index int64) error { + _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) + return err +} + +// 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/release.go b/vendor/code.gitea.io/sdk/gitea/release.go new file mode 100644 index 0000000000000..396251dcac9d8 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -0,0 +1,105 @@ +// 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"` + // swagger:strfmt date-time + CreatedAt time.Time `json:"created_at"` + // swagger:strfmt date-time + PublishedAt time.Time `json:"published_at"` + Publisher *User `json:"author"` + Attachments []*Attachment `json:"assets"` +} + +// ListReleases list releases of a repository +func (c *Client) ListReleases(user, repo string) ([]*Release, error) { + releases := make([]*Release, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases", user, repo), + 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 { + // required: true + TagName string `json:"tag_name" binding:"Required"` + 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 0000000000000..339cbd33deaac --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -0,0 +1,155 @@ +// 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" + "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"` + 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + Permissions *Permission `json:"permissions,omitempty"` +} + +// ListMyRepos lists all repositories for the authenticated user that has access to. +func (c *Client) ListMyRepos() ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos) +} + +// ListUserRepos list all repositories of one user by user's name +func (c *Client) ListUserRepos(user string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos", user), nil, nil, &repos) +} + +// ListOrgRepos list all repositories of one organization by organization's name +func (c *Client) ListOrgRepos(org string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos", org), nil, nil, &repos) +} + +// CreateRepoOption options when creating repository +// swagger:model +type CreateRepoOption struct { + // Name of the repository to create + // + // required: true + // unique: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(100)"` + // Description of the repository to create + Description string `json:"description" binding:"MaxSize(255)"` + // Whether the repository is private + Private bool `json:"private"` + // 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"` +} + +// 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) +} + +// 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 { + // required: true + CloneAddr string `json:"clone_addr" binding:"Required"` + AuthUsername string `json:"auth_username"` + AuthPassword string `json:"auth_password"` + // required: true + UID int `json:"uid" binding:"Required"` + // required: true + RepoName string `json:"repo_name" binding:"Required"` + 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 0000000000000..481fc3386ee76 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch.go @@ -0,0 +1,27 @@ +// 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 ( + "fmt" +) + +// Branch represents a repository branch +type Branch struct { + Name string `json:"name"` + Commit *PayloadCommit `json:"commit"` +} + +// ListRepoBranches list all the branches of one repository +func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) { + branches := make([]*Branch, 0, 10) + return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches) +} + +// GetRepoBranch get one branch's information of one repository +func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { + b := new(Branch) + return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b) +} 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 0000000000000..bd61a22cec4f5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -0,0 +1,57 @@ +// 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" +) + +// ListCollaborators list a repository's collaborators +func (c *Client) ListCollaborators(user, repo string) ([]*User, error) { + collaborators := make([]*User, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/collaborators", user, repo), + nil, nil, &collaborators) + return collaborators, err +} + +// IsCollaborator check if a user is a collaborator of a repository +func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { + status, err := c.getStatusCode("GET", + fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), + nil, nil) + 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), nil, 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_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go new file mode 100644 index 0000000000000..e6c89f0c0f28b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_file.go @@ -0,0 +1,15 @@ +// 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" +) + +// 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) +} 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 0000000000000..ec53311bdaa55 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_key.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 ( + "bytes" + "encoding/json" + "fmt" + "time" +) + +// DeployKey a deploy key +type DeployKey struct { + ID int64 `json:"id"` + Key string `json:"key"` + URL string `json:"url"` + Title string `json:"title"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + ReadOnly bool `json:"read_only"` +} + +// ListDeployKeys list all the deploy keys of one repository +func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) { + keys := make([]*DeployKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys) +} + +// 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) +} + +// CreateKeyOption options when creating a key +type CreateKeyOption struct { + // Title of the key to add + // + // required: true + // unique: true + Title string `json:"title" binding:"Required"` + // An armored SSH key to add + // + // required: true + // unique: true + Key string `json:"key" binding:"Required"` + // Describe if the key has only read access or read/write + // + // required: false + ReadOnly bool `json:"read_only"` +} + +// 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_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go new file mode 100644 index 0000000000000..1005f9fbd84ea --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_watch.go @@ -0,0 +1,41 @@ +// 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, pass string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &repos) +} + +// WatchRepo start to watch a repository +func (c *Client) WatchRepo(user, pass, repoUser, repoName string) (*WatchInfo, error) { + i := new(WatchInfo) + return i, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, i) +} + +// UnWatchRepo start to watch a repository +func (c *Client) UnWatchRepo(user, pass, repoUser, repoName string) (int, error) { + return c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil) +} 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 0000000000000..3060ab1b2b23b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/status.go @@ -0,0 +1,97 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` +} + +// 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"` +} + +// 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"` +} + +// ListStatusesOption holds pagination information +type ListStatusesOption struct { + Page int +} + +// CreateStatus creates a new Status for a given Commit +// +// POST /repos/:owner/:repo/statuses/:sha +func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { + body, err := json.Marshal(&opts) + if err != nil { + return nil, err + } + status := &Status{} + return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), + jsonHeader, bytes.NewReader(body), status) +} + +// ListStatuses returns all statuses for a given Commit +// +// GET /repos/:owner/:repo/commits/:ref/statuses +func (c *Client) ListStatuses(owner, repo, sha string, opts ListStatusesOption) ([]*Status, error) { + statuses := make([]*Status, 0, 10) + return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?page=%d", owner, repo, sha, opts.Page), nil, nil, &statuses) +} + +// GetCombinedStatus returns the CombinedStatus for a given Commit +// +// GET /repos/:owner/:repo/commits/:ref/status +func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { + status := &CombinedStatus{} + 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 0000000000000..57cf752316660 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user.go @@ -0,0 +1,51 @@ +// 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 ( + "encoding/json" + "fmt" +) + +// User represents a user +// swagger:model +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"` + // swagger:strfmt email + Email string `json:"email"` + // URL to the user's avatar + AvatarURL string `json:"avatar_url"` + // User locale + Language string `json:"language"` +} + +// MarshalJSON implements the json.Marshaler interface for User, adding field(s) for backward compatibility +func (u User) MarshalJSON() ([]byte, error) { + // Re-declaring User to avoid recursion + type shadow User + return json.Marshal(struct { + shadow + CompatUserName string `json:"username"` + }{shadow(u), u.UserName}) +} + +// 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 0000000000000..d3bfce971bad4 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_app.go @@ -0,0 +1,63 @@ +// 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/base64" + "encoding/json" + "fmt" + "net/http" +) + +// BasicAuthEncode generate base64 of basic auth head +func BasicAuthEncode(user, pass string) string { + return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass)) +} + +// AccessToken represents a API access token. +// swagger:response AccessToken +type AccessToken struct { + ID int64 `json:"id"` + Name string `json:"name"` + Sha1 string `json:"sha1"` +} + +// AccessTokenList represents a list of API access token. +// swagger:response AccessTokenList +type AccessTokenList []*AccessToken + +// ListAccessTokens lista all the access tokens of user +func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) { + tokens := make([]*AccessToken, 0, 10) + return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens) +} + +// CreateAccessTokenOption options when create access token +// swagger:parameters userCreateToken +type CreateAccessTokenOption struct { + Name string `json:"name" binding:"Required"` +} + +// CreateAccessToken create one access token with options +func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + t := new(AccessToken) + return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user), + http.Header{ + "content-type": []string{"application/json"}, + "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, + bytes.NewReader(body), t) +} + +// DeleteAccessToken delete token with key id +func (c *Client) DeleteAccessToken(user string, keyID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, 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 0000000000000..721f52144ba11 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_email.go @@ -0,0 +1,56 @@ +// 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" +) + +// Email an email address belonging to a user +type Email struct { + // swagger:strfmt email + Email string `json:"email"` + Verified bool `json:"verified"` + Primary bool `json:"primary"` +} + +// ListEmails all the email addresses of user +func (c *Client) ListEmails() ([]*Email, error) { + emails := make([]*Email, 0, 3) + return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails) +} + +// 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 0000000000000..a197a7f188220 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_follow.go @@ -0,0 +1,55 @@ +// 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" + +// ListMyFollowers list all the followers of current user +func (c *Client) ListMyFollowers(page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users) +} + +// ListFollowers list all the followers of one user +func (c *Client) ListFollowers(user string, page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users) +} + +// ListMyFollowing list all the users current user followed +func (c *Client) ListMyFollowing(page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users) +} + +// ListFollowing list all the users the user followed +func (c *Client) ListFollowing(user string, page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users) +} + +// 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 0000000000000..0817d89461a1c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go @@ -0,0 +1,80 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at,omitempty"` + // swagger:strfmt date-time + Expires time.Time `json:"expires_at,omitempty"` +} + +// GPGKeyEmail an email attached to a GPGKey +// swagger:model GPGKeyEmail +type GPGKeyEmail struct { + Email string `json:"email"` + Verified bool `json:"verified"` +} + +// CreateGPGKeyOption options create user GPG key +type CreateGPGKeyOption struct { + // An armored GPG key to add + // + // required: true + // unique: true + ArmoredKey string `json:"armored_public_key" binding:"Required"` +} + +// ListGPGKeys list all the GPG keys of the user +func (c *Client) ListGPGKeys(user string) ([]*GPGKey, error) { + keys := make([]*GPGKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys", user), nil, nil, &keys) +} + +// ListMyGPGKeys list all the GPG keys of current user +func (c *Client) ListMyGPGKeys() ([]*GPGKey, error) { + keys := make([]*GPGKey, 0, 10) + return keys, c.getParsedResponse("GET", "/user/gpg_keys", nil, nil, &keys) +} + +// 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) +} + +// 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 0000000000000..4488c033f1a37 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_key.go @@ -0,0 +1,57 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at,omitempty"` +} + +// ListPublicKeys list all the public keys of the user +func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) { + keys := make([]*PublicKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys) +} + +// ListMyPublicKeys list all the public keys of current user +func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) { + keys := make([]*PublicKey, 0, 10) + return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys) +} + +// 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) +} + +// 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 0000000000000..65ab980d66f86 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_search.go @@ -0,0 +1,14 @@ +package gitea + +import "fmt" + +type searchUsersResponse struct { + Users []*User `json:"data"` +} + +// SearchUsers finds users by query +func (c *Client) SearchUsers(query string, limit int) ([]*User, error) { + resp := new(searchUsersResponse) + err := c.getParsedResponse("GET", fmt.Sprintf("/users/search?q=%s&limit=%d", query, limit), nil, nil, &resp) + return resp.Users, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/utils.go b/vendor/code.gitea.io/sdk/gitea/utils.go new file mode 100644 index 0000000000000..80892a1e7a90b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/utils.go @@ -0,0 +1,26 @@ +// 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 ( + "net/http" +) + +var jsonHeader = http.Header{"content-type": []string{"application/json"}} + +// Bool return address of bool value +func Bool(v bool) *bool { + return &v +} + +// String return address of string value +func String(v string) *string { + return &v +} + +// Int64 return address of int64 value +func Int64(v int64) *int64 { + return &v +} diff --git a/vendor/github.com/Unknwon/cae/tz/testdata/test.lnk b/vendor/github.com/Unknwon/cae/tz/testdata/test.lnk deleted file mode 120000 index b317dc9d26172..0000000000000 --- a/vendor/github.com/Unknwon/cae/tz/testdata/test.lnk +++ /dev/null @@ -1 +0,0 @@ -test.zip \ No newline at end of file diff --git a/vendor/github.com/Unknwon/cae/tz/testdata/testdir.lnk b/vendor/github.com/Unknwon/cae/tz/testdata/testdir.lnk deleted file mode 120000 index 9f6260d6f524c..0000000000000 --- a/vendor/github.com/Unknwon/cae/tz/testdata/testdir.lnk +++ /dev/null @@ -1 +0,0 @@ -testdir \ No newline at end of file diff --git a/vendor/github.com/Unknwon/cae/zip/testdata/test.lnk b/vendor/github.com/Unknwon/cae/zip/testdata/test.lnk deleted file mode 120000 index b317dc9d26172..0000000000000 --- a/vendor/github.com/Unknwon/cae/zip/testdata/test.lnk +++ /dev/null @@ -1 +0,0 @@ -test.zip \ No newline at end of file diff --git a/vendor/github.com/Unknwon/cae/zip/testdata/testdir.lnk b/vendor/github.com/Unknwon/cae/zip/testdata/testdir.lnk deleted file mode 120000 index 9f6260d6f524c..0000000000000 --- a/vendor/github.com/Unknwon/cae/zip/testdata/testdir.lnk +++ /dev/null @@ -1 +0,0 @@ -testdir \ No newline at end of file diff --git a/vendor/gopkg.in/macaron.v1/fixtures/symlink b/vendor/gopkg.in/macaron.v1/fixtures/symlink deleted file mode 120000 index ea5233d8e939a..0000000000000 --- a/vendor/gopkg.in/macaron.v1/fixtures/symlink +++ /dev/null @@ -1 +0,0 @@ -basic \ No newline at end of file From 51778344a5c7008a4446af6200cfc492ed0e5d1f Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 21:56:31 +0800 Subject: [PATCH 03/21] remove update-issue-priority api temporarily UpdateIssuePriority is split into two APIs: PinIssue & UnpinIssue Signed-off-by: BetaCat0 outman99@hotmail.com --- models/issus_priority.go | 16 ++--- models/issus_priority_test.go | 10 +--- routers/api/v1/api.go | 4 +- routers/api/v1/repo/issue.go | 92 ++++++++++++++++++++++------- routers/repo/issue.go | 10 ++++ routers/repo/issue_test.go | 16 ++--- routers/routes/routes.go | 3 +- templates/swagger/v1_json.tmpl | 104 +++++++++++++++++++++++++++++++++ 8 files changed, 204 insertions(+), 51 deletions(-) diff --git a/models/issus_priority.go b/models/issus_priority.go index 07facb9d2bd71..13ce43f331d7f 100644 --- a/models/issus_priority.go +++ b/models/issus_priority.go @@ -9,16 +9,10 @@ import ( ) const ( - // LowestPriority defines the lowest-level priority - LowestPriority = iota + 1 - // LowPriority defines the low-level priority - LowPriority - // MediumPriority defines the medium-level priority - MediumPriority - // HighPriority defines the high-level priority - HighPriority - // HighestPriority defines the highest-level priority - HighestPriority + // PriorityDefault defines the default priority + PriorityDefault = 0 + // PriorityDefault defines the pinned priority + PriorityPinned = 10 ) // UpdateIssuePriority update priority for a specific issue @@ -33,7 +27,7 @@ func UpdateIssuePriority(issue *Issue, doer *User) error { return ErrUserDoesNotHaveAccessToRepo{UserID: doer.ID, RepoName: issue.Repo.Name} } - if issue.Priority > HighestPriority || issue.Priority < LowestPriority { + if issue.Priority < PriorityDefault { return ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority} } diff --git a/models/issus_priority_test.go b/models/issus_priority_test.go index 86fa6b818afd3..82b8ff9dedf80 100644 --- a/models/issus_priority_test.go +++ b/models/issus_priority_test.go @@ -17,23 +17,17 @@ func TestUpdateIssuePriority(t *testing.T) { repo := AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) doer := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) - issue.Priority = HighestPriority + issue.Priority = PriorityPinned err := UpdateIssuePriority(issue, doer) assert.NoError(t, err) issue = AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - assert.EqualValues(t, HighestPriority, issue.Priority) + assert.EqualValues(t, PriorityPinned, issue.Priority) issue.Priority = -1 err = UpdateIssuePriority(issue, doer) assert.Error(t, err) assert.EqualValues( t, err, ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) - - issue.Priority = 6 - err = UpdateIssuePriority(issue, doer) - assert.Error(t, err) - assert.EqualValues( - t, err, ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index a1a03de922bbf..b70c0804c42f1 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -457,8 +457,8 @@ func RegisterRoutes(m *macaron.Macaron) { }) m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) - - m.Combo("/priority").Patch(reqToken(), bind(api.EditPriorityOption{}), repo.UpdateIssuePriority) + m.Combo("/deadline").Patch(reqToken(), repo.PinIssue) + m.Combo("/priority").Patch(reqToken(), repo.UnpinIssue) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 827228bff7ad4..cc2bf878fdf00 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -178,7 +178,6 @@ func CreateIssue(ctx *context.APIContext, form api.CreateIssueOption) { Poster: ctx.User, Content: form.Body, DeadlineUnix: deadlineUnix, - Priority: models.LowestPriority, } var assigneeIDs = make([]int64, 0) @@ -418,12 +417,12 @@ func UpdateIssueDeadline(ctx *context.APIContext, form api.EditDeadlineOption) { ctx.JSON(201, api.IssueDeadline{Deadline: form.Deadline}) } -// UpdateIssuePriority updates an issue priority. -func UpdateIssuePriority(ctx *context.APIContext, form api.EditPriorityOption) { - // swagger:operation PATCH /repos/{owner}/{repo}/issues/{index}/priority issue issueUpdateIssuePriority +// PinIssue pin an issue +func PinIssue(ctx *context.APIContext) { + // swagger:operation PATCH /repos/{owner}/{repo}/issues/{index}/pin issue issuePinIssue // --- - // summary: Update the priority of an issue. - // consumes: + // summary: Pin an issue + // produces: // - application/json // parameters: // - name: owner @@ -438,16 +437,12 @@ func UpdateIssuePriority(ctx *context.APIContext, form api.EditPriorityOption) { // required: true // - name: index // in: path - // description: index of the issue to update priority on + // description: index of the issue to pin // type: integer // required: true - // - name: body - // in: body - // schema: - // "$ref": "#/definitions/EditPriorityOption" // responses: // "200": - // "$ref": "#/responses/Issue" + // "$ref": "#/responses/empty" // "403": // description: Not repo writer // schema: @@ -460,31 +455,84 @@ func UpdateIssuePriority(ctx *context.APIContext, form api.EditPriorityOption) { issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) if err != nil { if models.IsErrIssueNotExist(err) { - ctx.Status(http.StatusNotFound) + ctx.Status(404) } else { - ctx.Error(http.StatusInternalServerError, "GetIssueByIndex", err) + ctx.Error(500, "GetIssueByIndex", err) } - return } if !ctx.Repo.IsWriter() { - ctx.Status(http.StatusForbidden) + ctx.Status(403) return } - if form.Priority < models.LowestPriority || form.Priority > models.HighestPriority { - ctx.Error(http.StatusInternalServerError, - "UpdateIssuePriority", fmt.Sprintf("Invalid priority [%v]", form.Priority)) + issue.Priority = models.PriorityPinned + if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + ctx.Error(500, "PinIssue", err) return } - if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { - ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err) + ctx.JSON(200, nil) +} +// UnpinIssue unpin an issue +func UnpinIssue(ctx *context.APIContext) { + // swagger:operation PATCH /repos/{owner}/{repo}/issues/{index}/unpin issue issueUnpinIssue + // --- + // summary: Unpin an issue + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue to unpin + // type: integer + // required: true + // responses: + // "200": + // "$ref": "#/responses/empty" + // "403": + // description: Not repo writer + // schema: + // "$ref": "#/responses/forbidden" + // "404": + // description: Issue not found + // schema: + // "$ref": "#/responses/empty" + + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index")) + if err != nil { + if models.IsErrIssueNotExist(err) { + ctx.Status(404) + } else { + ctx.Error(500, "GetIssueByIndex", err) + } + return + } + + if !ctx.Repo.IsWriter() { + ctx.Status(403) + return + } + + issue.Priority = models.PriorityDefault + + if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + ctx.Error(500, "UnpinIssue", err) return } - ctx.JSON(http.StatusOK, issue.APIFormat()) + ctx.JSON(200, nil) } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index b4b860d73728a..b41af0e2ece4b 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -1559,3 +1559,13 @@ func UpdateIssuePriority(ctx *context.Context, form auth.EditPriorityForm) { ctx.JSON(http.StatusOK, tplIssues) } + +// PinIssue pin an issue by index +func PinIssue(ctx *context.Context) { + UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: models.PriorityPinned}) +} + +// UnpinIssue pin an issue by index +func UnpinIssue(ctx *context.Context) { + UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: models.PriorityDefault}) +} diff --git a/routers/repo/issue_test.go b/routers/repo/issue_test.go index a5360edf2691e..6f7075c4686e2 100644 --- a/routers/repo/issue_test.go +++ b/routers/repo/issue_test.go @@ -9,7 +9,6 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/modules/auth" "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" ) @@ -17,20 +16,23 @@ import ( func TestUpdateIssuePriority(t *testing.T) { models.PrepareTestEnv(t) - ctx := test.MockContext(t, "user2/repo1/issues/1/priority") + ctx := test.MockContext(t, "user2/repo1/issues/1/pin") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) test.LoadGitRepo(t, ctx) - UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: 2}) + PinIssue(ctx) assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Issue{ ID: 1, - }, models.Cond("priority = ?", 2)) + }, models.Cond("priority = ?", models.PriorityPinned)) - ctx = test.MockContext(t, "user2/repo1/issues/1/priority") + ctx = test.MockContext(t, "user2/repo1/issues/1/unpin") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) test.LoadGitRepo(t, ctx) - UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: -1}) - assert.EqualValues(t, http.StatusInternalServerError, ctx.Resp.Status()) + UnpinIssue(ctx) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + models.AssertExistsAndLoadBean(t, &models.Issue{ + ID: 1, + }, models.Cond("priority = ?", models.PriorityDefault)) } diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 800df0cceed06..8109b5e83bebf 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -537,7 +537,8 @@ func RegisterRoutes(m *macaron.Macaron) { }) }) m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction) - m.Patch("/priority", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.UpdateIssuePriority) + m.Patch("/pin", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.PinIssue) + m.Patch("/unpin", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.UnpinIssue) }) m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel) diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index 598813bfc0047..284c0bcbf23bb 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -2618,6 +2618,110 @@ } } }, + "/repos/{owner}/{repo}/issues/{index}/pin": { + "patch": { + "produces": [ + "application/json" + ], + "tags": [ + "issue" + ], + "summary": "Pin an issue", + "operationId": "issuePinIssue", + "parameters": [ + { + "type": "string", + "description": "owner of the repo", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "name of the repo", + "name": "repo", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "index of the issue to pin", + "name": "index", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/empty" + }, + "403": { + "description": "Not repo writer", + "schema": { + "$ref": "#/responses/forbidden" + } + }, + "404": { + "description": "Issue not found", + "schema": { + "$ref": "#/responses/empty" + } + } + } + } + }, + "/repos/{owner}/{repo}/issues/{index}/unpin": { + "patch": { + "produces": [ + "application/json" + ], + "tags": [ + "issue" + ], + "summary": "Unpin an issue", + "operationId": "issueUnpinIssue", + "parameters": [ + { + "type": "string", + "description": "owner of the repo", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "name of the repo", + "name": "repo", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "index of the issue to unpin", + "name": "index", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/empty" + }, + "403": { + "description": "Not repo writer", + "schema": { + "$ref": "#/responses/forbidden" + } + }, + "404": { + "description": "Issue not found", + "schema": { + "$ref": "#/responses/empty" + } + } + } + } + }, "/repos/{owner}/{repo}/keys": { "get": { "produces": [ From b38e7334a9a881384356dbb6ab2db84733ee64ac Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 22:06:20 +0800 Subject: [PATCH 04/21] fix comments Signed-off-by: BetaCat0 outman99@hotmail.com --- models/error.go | 2 +- models/issus_priority.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/models/error.go b/models/error.go index 492f80214cb69..7a8d5046a3ac3 100644 --- a/models/error.go +++ b/models/error.go @@ -884,7 +884,7 @@ type ErrIssueInvalidPriority struct { DesiredPriority int } -// ErrIssueInvalidPriority checks if an error is a ErrIssueInvalidPriority. +// IsErrIssueInvalidPriority checks if an error is a ErrIssueInvalidPriority. func IsErrIssueInvalidPriority(err error) bool { _, ok := err.(ErrIssueInvalidPriority) return ok diff --git a/models/issus_priority.go b/models/issus_priority.go index 13ce43f331d7f..9890a442642bf 100644 --- a/models/issus_priority.go +++ b/models/issus_priority.go @@ -11,7 +11,7 @@ import ( const ( // PriorityDefault defines the default priority PriorityDefault = 0 - // PriorityDefault defines the pinned priority + // PriorityPinned defines the pinned priority PriorityPinned = 10 ) From 8a021f2ed9cd18af27b9ff73302e9ac3037e3101 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Fri, 31 Aug 2018 00:37:33 +0800 Subject: [PATCH 05/21] fix issues & bug issue-unpin will auto trigger when issues close Signed-off-by: BetaCat0 outman99@hotmail.com --- models/issue.go | 1 + models/issus_priority.go | 40 ++++++++++++++++++++++++++++------- models/issus_priority_test.go | 12 +++++------ routers/api/v1/api.go | 4 ++-- routers/api/v1/repo/issue.go | 6 ++---- routers/repo/issue.go | 15 +++++++++++-- routers/repo/issue_test.go | 2 +- 7 files changed, 56 insertions(+), 24 deletions(-) diff --git a/models/issue.go b/models/issue.go index 0039498e7b81a..a0a206faf235b 100644 --- a/models/issue.go +++ b/models/issue.go @@ -665,6 +665,7 @@ func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, issue.IsClosed = isClosed if isClosed { + issue.Priority = PriorityDefault issue.ClosedUnix = util.TimeStampNow() } else { issue.ClosedUnix = 0 diff --git a/models/issus_priority.go b/models/issus_priority.go index 9890a442642bf..31c672e5bb224 100644 --- a/models/issus_priority.go +++ b/models/issus_priority.go @@ -11,12 +11,27 @@ import ( const ( // PriorityDefault defines the default priority PriorityDefault = 0 - // PriorityPinned defines the pinned priority - PriorityPinned = 10 ) // UpdateIssuePriority update priority for a specific issue -func UpdateIssuePriority(issue *Issue, doer *User) error { +func UpdateIssuePriority(issue *Issue) error { + if err := issue.loadRepo(x); err != nil { + return err + } + + if issue.Priority < PriorityDefault { + return ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority} + } + + _, err := AutoTransaction(func(session *xorm.Session) (interface{}, error) { + return nil, updateIssueCols(session, &Issue{ID: issue.ID, Priority: issue.Priority}, "priority") + }, x) + + return err +} + +// PinIssue to pin an issue +func PinIssue(issue *Issue, doer *User) error { if err := issue.loadRepo(x); err != nil { return err } @@ -27,12 +42,21 @@ func UpdateIssuePriority(issue *Issue, doer *User) error { return ErrUserDoesNotHaveAccessToRepo{UserID: doer.ID, RepoName: issue.Repo.Name} } - if issue.Priority < PriorityDefault { - return ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority} - } - _, err := AutoTransaction(func(session *xorm.Session) (interface{}, error) { - return nil, updateIssueCols(session, &Issue{ID: issue.ID, Priority: issue.Priority}, "priority") + var p int64 + _, err := session.Table("issue"). + Select("MAX(priority)").Where("repo_id=? and is_pull=0", issue.Repo.ID).Get(&p) + if err != nil { + return nil, err + } + + _, err = session.Table("issue").Where("id = ?", issue.ID). + Update(map[string]interface{}{"priority": p + 10}) + if err != nil { + return nil, err + } + + return nil, nil }, x) return err diff --git a/models/issus_priority_test.go b/models/issus_priority_test.go index 82b8ff9dedf80..faa6a646f85bd 100644 --- a/models/issus_priority_test.go +++ b/models/issus_priority_test.go @@ -17,17 +17,15 @@ func TestUpdateIssuePriority(t *testing.T) { repo := AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) doer := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) - issue.Priority = PriorityPinned - - err := UpdateIssuePriority(issue, doer) + err := PinIssue(issue, doer) assert.NoError(t, err) issue = AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - assert.EqualValues(t, PriorityPinned, issue.Priority) + assert.EqualValues(t, 15, issue.Priority) issue.Priority = -1 - err = UpdateIssuePriority(issue, doer) + err = UpdateIssuePriority(issue) assert.Error(t, err) - assert.EqualValues( - t, err, ErrIssueInvalidPriority{ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) + assert.EqualValues(t, err, ErrIssueInvalidPriority{ + ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index b70c0804c42f1..fcb15c3f0017e 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -457,8 +457,8 @@ func RegisterRoutes(m *macaron.Macaron) { }) m.Combo("/deadline").Post(reqToken(), bind(api.EditDeadlineOption{}), repo.UpdateIssueDeadline) - m.Combo("/deadline").Patch(reqToken(), repo.PinIssue) - m.Combo("/priority").Patch(reqToken(), repo.UnpinIssue) + m.Combo("/pin").Patch(reqToken(), repo.PinIssue) + m.Combo("/unpin").Patch(reqToken(), repo.UnpinIssue) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index cc2bf878fdf00..4d82f5ca97142 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -467,9 +467,7 @@ func PinIssue(ctx *context.APIContext) { return } - issue.Priority = models.PriorityPinned - - if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + if err := models.PinIssue(issue, ctx.User); err != nil { ctx.Error(500, "PinIssue", err) return } @@ -529,7 +527,7 @@ func UnpinIssue(ctx *context.APIContext) { issue.Priority = models.PriorityDefault - if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + if err := models.UpdateIssuePriority(issue); err != nil { ctx.Error(500, "UnpinIssue", err) return } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index b41af0e2ece4b..8fab8eff61257 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -1551,7 +1551,7 @@ func UpdateIssuePriority(ctx *context.Context, form auth.EditPriorityForm) { issue.Priority = form.Priority - if err := models.UpdateIssuePriority(issue, ctx.User); err != nil { + if err := models.UpdateIssuePriority(issue); err != nil { ctx.Error(http.StatusInternalServerError) return @@ -1562,7 +1562,18 @@ func UpdateIssuePriority(ctx *context.Context, form auth.EditPriorityForm) { // PinIssue pin an issue by index func PinIssue(ctx *context.Context) { - UpdateIssuePriority(ctx, auth.EditPriorityForm{Priority: models.PriorityPinned}) + issue := GetActionIssue(ctx) + if ctx.Written() { + return + } + + if err := models.PinIssue(issue, ctx.User); err != nil { + ctx.Error(http.StatusInternalServerError) + + return + } + + ctx.JSON(http.StatusOK, tplIssues) } // UnpinIssue pin an issue by index diff --git a/routers/repo/issue_test.go b/routers/repo/issue_test.go index 6f7075c4686e2..88c2fa6fbeeeb 100644 --- a/routers/repo/issue_test.go +++ b/routers/repo/issue_test.go @@ -24,7 +24,7 @@ func TestUpdateIssuePriority(t *testing.T) { assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Issue{ ID: 1, - }, models.Cond("priority = ?", models.PriorityPinned)) + }, models.Cond("priority = ?", 15)) ctx = test.MockContext(t, "user2/repo1/issues/1/unpin") test.LoadUser(t, ctx, 2) From 52109e3d3c2a93427062d7e6ae4b47697e38e932 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Fri, 31 Aug 2018 12:53:00 +0800 Subject: [PATCH 06/21] fix issue --- models/issue.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/issue.go b/models/issue.go index a0a206faf235b..ebb32735a14c0 100644 --- a/models/issue.go +++ b/models/issue.go @@ -671,7 +671,7 @@ func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, issue.ClosedUnix = 0 } - if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil { + if err = updateIssueCols(e, issue, "is_closed", "closed_unix", "priority"); err != nil { return err } From 461046b9aff610677df564c55959dd37caaed27b Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 04:10:53 +0800 Subject: [PATCH 07/21] Web UI for issue pin/unpin --- public/js/index.js | 22 ++++++++++++++++++++++ routers/repo/issue.go | 1 + routers/routes/routes.go | 4 ++-- templates/repo/issue/list.tmpl | 16 +++++++++++++--- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/public/js/index.js b/public/js/index.js index c90e129ce36b6..4cde8dc6791df 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -117,6 +117,14 @@ function updateIssuesMeta(url, action, issueIds, elementId, afterSuccess) { }) } +function updateIssuePriority(url, afterSuccess) { + $.ajax({ + type: "PATCH", + url: url, + success: afterSuccess + }) +} + function initReactionSelector(parent) { var reactions = ''; if (!parent) { @@ -1864,6 +1872,20 @@ $(document).ready(function () { }); }); + $('.issue-pin').click(function () { + var url = this.dataset.url + updateIssuePriority(url, function() { + location.reload(); + }); + }); + + $('.issue-unpin').click(function () { + var url = this.dataset.url + updateIssuePriority(url, function() { + location.reload(); + }); + }); + buttonsClickOnEnter(); searchUsers(); searchRepositories(); diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 8fab8eff61257..718054ee1ad36 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -248,6 +248,7 @@ func Issues(ctx *context.Context) { ctx.Data["AssigneeID"] = assigneeID ctx.Data["IsShowClosed"] = isShowClosed ctx.Data["Keyword"] = keyword + ctx.Data["IsWriter"] = ctx.Repo.IsWriter() if isShowClosed { ctx.Data["State"] = "closed" } else { diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 8109b5e83bebf..ac09cfdba540c 100644 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -537,8 +537,8 @@ func RegisterRoutes(m *macaron.Macaron) { }) }) m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction) - m.Patch("/pin", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.PinIssue) - m.Patch("/unpin", reqRepoWriter, context.RepoRef(), context.CheckAnyUnit(models.UnitTypeIssues), repo.UnpinIssue) + m.Patch("/pin", reqRepoWriter, repo.PinIssue) + m.Patch("/unpin", reqRepoWriter, repo.UnpinIssue) }) m.Post("/labels", reqRepoWriter, repo.UpdateIssueLabel) diff --git a/templates/repo/issue/list.tmpl b/templates/repo/issue/list.tmpl index 40a56b1b32b26..68e91636290bb 100644 --- a/templates/repo/issue/list.tmpl +++ b/templates/repo/issue/list.tmpl @@ -181,9 +181,11 @@ {{range .Issues}} {{ $timeStr:= TimeSinceUnix .CreatedUnix $.Lang }}
  • -
    - -
    + {{if $.IsWriter}} +
    + +
    + {{end}}
    #{{.Index}}
    {{.Title}} @@ -194,6 +196,14 @@ {{.Name}} {{end}} + {{if $.IsWriter}} + {{if eq .Priority 0}} +
    pin
    + {{else}} +
    unpin
    + {{end}} + {{end}} + {{if .NumComments}} {{.NumComments}} {{end}} From f9297e56a6ee2bcc71413b0f8c7b76b6e4aae263 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 04:27:31 +0800 Subject: [PATCH 08/21] update vendor --- Gopkg.lock | 2 +- vendor/code.gitea.io/sdk/gitea/issue.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Gopkg.lock b/Gopkg.lock index 9076a0c839a0a..f33035a5b0d40 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -11,7 +11,7 @@ branch = "master" name = "code.gitea.io/sdk" packages = ["gitea"] - revision = "021567c9c12fe289b8980c34e81e6684434dd082" + revision = "aa2397dec8f9e598972e0de51135393049e46bbb" [[projects]] name = "github.com/PuerkitoBio/goquery" diff --git a/vendor/code.gitea.io/sdk/gitea/issue.go b/vendor/code.gitea.io/sdk/gitea/issue.go index fee7cd6f9fca2..8fc2b2bf7b137 100644 --- a/vendor/code.gitea.io/sdk/gitea/issue.go +++ b/vendor/code.gitea.io/sdk/gitea/issue.go @@ -152,3 +152,9 @@ type IssueDeadline struct { // swagger:strfmt date-time Deadline *time.Time `json:"due_date"` } + +// EditPriorityOption options for updating priority +type EditPriorityOption struct { + // required:true + Priority int `json:"priority"` +} From ee58221d60cc0c57e0f72633c99a04de4a6154e3 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 21:30:32 +0800 Subject: [PATCH 09/21] update vendor --- Gopkg.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gopkg.lock b/Gopkg.lock index f33035a5b0d40..f53c2f1c227c6 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -11,7 +11,7 @@ branch = "master" name = "code.gitea.io/sdk" packages = ["gitea"] - revision = "aa2397dec8f9e598972e0de51135393049e46bbb" + revision = "8718470818c8dede6a95a9263137b6fddcf16bf3" [[projects]] name = "github.com/PuerkitoBio/goquery" From 5d3c90074375050bd12f7b878ed25a3c8c5fec1c Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 21:35:38 +0800 Subject: [PATCH 10/21] append -v to make vendor: to show what's actually going on during vendor updating. --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4eb5873e42147..3bc4371c83f2c 100644 --- a/Makefile +++ b/Makefile @@ -177,7 +177,7 @@ vendor: @hash dep > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ $(GO) get -u github.com/golang/dep/cmd/dep; \ fi - dep ensure -vendor-only + dep ensure -vendor-only -v .PHONY: test-vendor test-vendor: vendor From c516e8e2b5c2ea86e1657fae8ebd2860e092b0e0 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 21:51:44 +0800 Subject: [PATCH 11/21] reset priority in fixtures/issue.yml --- models/fixtures/issue.yml | 12 ++++++------ models/issus_priority_test.go | 21 +++++++++++++++++---- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/models/fixtures/issue.yml b/models/fixtures/issue.yml index 45ccf2b486d20..3defeb04c2a5d 100644 --- a/models/fixtures/issue.yml +++ b/models/fixtures/issue.yml @@ -4,7 +4,7 @@ index: 1 poster_id: 1 name: issue1 - priority: 1 + priority: 0 content: content for the first issue is_closed: false is_pull: false @@ -18,7 +18,7 @@ index: 2 poster_id: 1 name: issue2 - priority: 2 + priority: 0 content: content for the second issue milestone_id: 1 is_closed: false @@ -33,7 +33,7 @@ index: 3 poster_id: 1 name: issue3 - priority: 3 + priority: 0 content: content for the third issue is_closed: false is_pull: true @@ -46,7 +46,7 @@ index: 1 poster_id: 2 name: issue4 - priority: 4 + priority: 0 content: content for the fourth issue is_closed: true is_pull: false @@ -59,7 +59,7 @@ index: 4 poster_id: 2 name: issue5 - priority: 5 + priority: 0 content: content for the fifth issue is_closed: true is_pull: false @@ -72,7 +72,7 @@ index: 1 poster_id: 1 name: issue6 - priority: 5 + priority: 0 content: content6 is_closed: false is_pull: false diff --git a/models/issus_priority_test.go b/models/issus_priority_test.go index faa6a646f85bd..38d187c65ad4e 100644 --- a/models/issus_priority_test.go +++ b/models/issus_priority_test.go @@ -14,14 +14,13 @@ func TestUpdateIssuePriority(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) issue := AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - repo := AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) - doer := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) - err := PinIssue(issue, doer) + issue.Priority = 99 + err := UpdateIssuePriority(issue) assert.NoError(t, err) issue = AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - assert.EqualValues(t, 15, issue.Priority) + assert.EqualValues(t, 99, issue.Priority) issue.Priority = -1 err = UpdateIssuePriority(issue) @@ -29,3 +28,17 @@ func TestUpdateIssuePriority(t *testing.T) { assert.EqualValues(t, err, ErrIssueInvalidPriority{ ID: issue.ID, RepoID: issue.Repo.ID, DesiredPriority: issue.Priority}) } + +func TestPinIssue(t *testing.T) { + assert.NoError(t, PrepareTestDatabase()) + + issue := AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + repo := AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) + doer := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + + err := PinIssue(issue, doer) + assert.NoError(t, err) + + issue = AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.EqualValues(t, 10, issue.Priority) +} From 9e726b922228f9fe4b233c6a1e233cc40255b954 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Sat, 1 Sep 2018 22:00:35 +0800 Subject: [PATCH 12/21] update test case --- routers/repo/issue_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/repo/issue_test.go b/routers/repo/issue_test.go index 88c2fa6fbeeeb..bca2a74c3bbbd 100644 --- a/routers/repo/issue_test.go +++ b/routers/repo/issue_test.go @@ -24,7 +24,7 @@ func TestUpdateIssuePriority(t *testing.T) { assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) models.AssertExistsAndLoadBean(t, &models.Issue{ ID: 1, - }, models.Cond("priority = ?", 15)) + }, models.Cond("priority = ?", 10)) ctx = test.MockContext(t, "user2/repo1/issues/1/unpin") test.LoadUser(t, ctx, 2) From 4083ee0fe7c6f975dbceb34d08e805253187d2ad Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 01:02:58 +0800 Subject: [PATCH 13/21] Priority updating api for issues (both web and api). Signed-off-by: BetaCat0 outman99@hotmail.com --- vendor/code.gitea.io/git/LICENSE | 20 - vendor/code.gitea.io/git/blob.go | 73 --- vendor/code.gitea.io/git/command.go | 134 ----- vendor/code.gitea.io/git/commit.go | 276 --------- vendor/code.gitea.io/git/commit_archive.go | 37 -- vendor/code.gitea.io/git/commit_info.go | 319 ----------- vendor/code.gitea.io/git/doc.go | 5 - vendor/code.gitea.io/git/error.go | 66 --- vendor/code.gitea.io/git/git.go | 91 --- vendor/code.gitea.io/git/hook.go | 126 ----- vendor/code.gitea.io/git/parse.go | 81 --- vendor/code.gitea.io/git/repo.go | 287 ---------- vendor/code.gitea.io/git/repo_blame.go | 24 - vendor/code.gitea.io/git/repo_branch.go | 123 ---- vendor/code.gitea.io/git/repo_commit.go | 352 ------------ vendor/code.gitea.io/git/repo_hook.go | 15 - vendor/code.gitea.io/git/repo_object.go | 19 - vendor/code.gitea.io/git/repo_pull.go | 89 --- vendor/code.gitea.io/git/repo_tag.go | 157 ------ vendor/code.gitea.io/git/repo_tree.go | 26 - vendor/code.gitea.io/git/sha1.go | 76 --- vendor/code.gitea.io/git/signature.go | 58 -- vendor/code.gitea.io/git/submodule.go | 79 --- vendor/code.gitea.io/git/tag.go | 89 --- vendor/code.gitea.io/git/tree.go | 72 --- vendor/code.gitea.io/git/tree_blob.go | 59 -- vendor/code.gitea.io/git/tree_entry.go | 200 ------- vendor/code.gitea.io/git/utils.go | 96 ---- vendor/code.gitea.io/sdk/LICENSE | 20 - vendor/code.gitea.io/sdk/gitea/admin_org.go | 22 - vendor/code.gitea.io/sdk/gitea/admin_repo.go | 22 - vendor/code.gitea.io/sdk/gitea/attachment.go | 92 --- vendor/code.gitea.io/sdk/gitea/doc.go | 5 - vendor/code.gitea.io/sdk/gitea/fork.go | 39 -- vendor/code.gitea.io/sdk/gitea/gitea.go | 104 ---- vendor/code.gitea.io/sdk/gitea/hook.go | 531 ------------------ .../code.gitea.io/sdk/gitea/issue_comment.go | 76 --- vendor/code.gitea.io/sdk/gitea/issue_label.go | 122 ---- .../sdk/gitea/issue_milestone.go | 80 --- .../sdk/gitea/issue_tracked_time.go | 68 --- vendor/code.gitea.io/sdk/gitea/lfs_lock.go | 65 --- .../code.gitea.io/sdk/gitea/miscellaneous.go | 52 -- vendor/code.gitea.io/sdk/gitea/org.go | 68 --- vendor/code.gitea.io/sdk/gitea/org_member.go | 26 - vendor/code.gitea.io/sdk/gitea/org_team.go | 32 -- vendor/code.gitea.io/sdk/gitea/pull.go | 151 ----- vendor/code.gitea.io/sdk/gitea/release.go | 105 ---- vendor/code.gitea.io/sdk/gitea/repo.go | 155 ----- vendor/code.gitea.io/sdk/gitea/repo_branch.go | 27 - .../sdk/gitea/repo_collaborator.go | 57 -- vendor/code.gitea.io/sdk/gitea/repo_file.go | 15 - vendor/code.gitea.io/sdk/gitea/repo_key.go | 69 --- vendor/code.gitea.io/sdk/gitea/repo_watch.go | 41 -- vendor/code.gitea.io/sdk/gitea/status.go | 97 ---- vendor/code.gitea.io/sdk/gitea/user.go | 51 -- vendor/code.gitea.io/sdk/gitea/user_app.go | 63 --- vendor/code.gitea.io/sdk/gitea/user_email.go | 56 -- vendor/code.gitea.io/sdk/gitea/user_follow.go | 55 -- vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 80 --- vendor/code.gitea.io/sdk/gitea/user_key.go | 57 -- vendor/code.gitea.io/sdk/gitea/user_search.go | 14 - vendor/code.gitea.io/sdk/gitea/utils.go | 26 - 62 files changed, 5592 deletions(-) delete mode 100644 vendor/code.gitea.io/git/LICENSE delete mode 100644 vendor/code.gitea.io/git/blob.go delete mode 100644 vendor/code.gitea.io/git/command.go delete mode 100644 vendor/code.gitea.io/git/commit.go delete mode 100644 vendor/code.gitea.io/git/commit_archive.go delete mode 100644 vendor/code.gitea.io/git/commit_info.go delete mode 100644 vendor/code.gitea.io/git/doc.go delete mode 100644 vendor/code.gitea.io/git/error.go delete mode 100644 vendor/code.gitea.io/git/git.go delete mode 100644 vendor/code.gitea.io/git/hook.go delete mode 100644 vendor/code.gitea.io/git/parse.go delete mode 100644 vendor/code.gitea.io/git/repo.go delete mode 100644 vendor/code.gitea.io/git/repo_blame.go delete mode 100644 vendor/code.gitea.io/git/repo_branch.go delete mode 100644 vendor/code.gitea.io/git/repo_commit.go delete mode 100644 vendor/code.gitea.io/git/repo_hook.go delete mode 100644 vendor/code.gitea.io/git/repo_object.go delete mode 100644 vendor/code.gitea.io/git/repo_pull.go delete mode 100644 vendor/code.gitea.io/git/repo_tag.go delete mode 100644 vendor/code.gitea.io/git/repo_tree.go delete mode 100644 vendor/code.gitea.io/git/sha1.go delete mode 100644 vendor/code.gitea.io/git/signature.go delete mode 100644 vendor/code.gitea.io/git/submodule.go delete mode 100644 vendor/code.gitea.io/git/tag.go delete mode 100644 vendor/code.gitea.io/git/tree.go delete mode 100644 vendor/code.gitea.io/git/tree_blob.go delete mode 100644 vendor/code.gitea.io/git/tree_entry.go delete mode 100644 vendor/code.gitea.io/git/utils.go delete mode 100644 vendor/code.gitea.io/sdk/LICENSE delete mode 100644 vendor/code.gitea.io/sdk/gitea/admin_org.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/admin_repo.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/attachment.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/doc.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/fork.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/gitea.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/hook.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_comment.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_label.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_milestone.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/lfs_lock.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/miscellaneous.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org_member.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/org_team.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/pull.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/release.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_branch.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_collaborator.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_file.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_key.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/repo_watch.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/status.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_app.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_email.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_follow.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_gpgkey.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_key.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/user_search.go delete mode 100644 vendor/code.gitea.io/sdk/gitea/utils.go diff --git a/vendor/code.gitea.io/git/LICENSE b/vendor/code.gitea.io/git/LICENSE deleted file mode 100644 index 10aeba46bcfc9..0000000000000 --- a/vendor/code.gitea.io/git/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -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/git/blob.go b/vendor/code.gitea.io/git/blob.go deleted file mode 100644 index a6e392eeb50a6..0000000000000 --- a/vendor/code.gitea.io/git/blob.go +++ /dev/null @@ -1,73 +0,0 @@ -// 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 git - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" -) - -// Blob represents a Git object. -type Blob struct { - repo *Repository - *TreeEntry -} - -// Data gets content of blob all at once and wrap it as io.Reader. -// This can be very slow and memory consuming for huge content. -func (b *Blob) Data() (io.Reader, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - - // Preallocate memory to save ~50% memory usage on big files. - stdout.Grow(int(b.Size() + 2048)) - - if err := b.DataPipeline(stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - return stdout, nil -} - -// DataPipeline gets content of blob and write the result or error to stdout or stderr -func (b *Blob) DataPipeline(stdout, stderr io.Writer) error { - return NewCommand("show", b.ID.String()).RunInDirPipeline(b.repo.Path, stdout, stderr) -} - -type cmdReadCloser struct { - cmd *exec.Cmd - stdout io.Reader -} - -func (c cmdReadCloser) Read(p []byte) (int, error) { - return c.stdout.Read(p) -} - -func (c cmdReadCloser) Close() error { - io.Copy(ioutil.Discard, c.stdout) - return c.cmd.Wait() -} - -// DataAsync gets a ReadCloser for the contents of a blob without reading it all. -// Calling the Close function on the result will discard all unread output. -func (b *Blob) DataAsync() (io.ReadCloser, error) { - cmd := exec.Command("git", "show", b.ID.String()) - cmd.Dir = b.repo.Path - cmd.Stderr = os.Stderr - - stdout, err := cmd.StdoutPipe() - if err != nil { - return nil, fmt.Errorf("StdoutPipe: %v", err) - } - - if err = cmd.Start(); err != nil { - return nil, fmt.Errorf("Start: %v", err) - } - - return cmdReadCloser{stdout: stdout, cmd: cmd}, nil -} diff --git a/vendor/code.gitea.io/git/command.go b/vendor/code.gitea.io/git/command.go deleted file mode 100644 index 8ca99fd6d3add..0000000000000 --- a/vendor/code.gitea.io/git/command.go +++ /dev/null @@ -1,134 +0,0 @@ -// 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 git - -import ( - "bytes" - "context" - "fmt" - "io" - "os/exec" - "strings" - "time" -) - -var ( - // GlobalCommandArgs global command args for external package setting - GlobalCommandArgs []string - - // DefaultCommandExecutionTimeout default command execution timeout duration - DefaultCommandExecutionTimeout = 60 * time.Second -) - -// Command represents a command with its subcommands or arguments. -type Command struct { - name string - args []string -} - -func (c *Command) String() string { - if len(c.args) == 0 { - return c.name - } - return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " ")) -} - -// NewCommand creates and returns a new Git Command based on given command and arguments. -func NewCommand(args ...string) *Command { - return &Command{ - name: "git", - args: append(GlobalCommandArgs, args...), - } -} - -// AddArguments adds new argument(s) to the command. -func (c *Command) AddArguments(args ...string) *Command { - c.args = append(c.args, args...) - return c -} - -// RunInDirTimeoutPipeline executes the command in given directory with given timeout, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error { - if timeout == -1 { - timeout = DefaultCommandExecutionTimeout - } - - if len(dir) == 0 { - log(c.String()) - } else { - log("%s: %v", dir, c) - } - - ctx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - - cmd := exec.CommandContext(ctx, c.name, c.args...) - cmd.Dir = dir - cmd.Stdout = stdout - cmd.Stderr = stderr - if err := cmd.Start(); err != nil { - return err - } - - if err := cmd.Wait(); err != nil { - return err - } - - return ctx.Err() -} - -// RunInDirTimeout executes the command in given directory with given timeout, -// and returns stdout in []byte and error (combined with stderr). -func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - if err := c.RunInDirTimeoutPipeline(timeout, dir, stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - - if stdout.Len() > 0 { - log("stdout:\n%s", stdout.Bytes()[:1024]) - } - return stdout.Bytes(), nil -} - -// RunInDirPipeline executes the command in given directory, -// it pipes stdout and stderr to given io.Writer. -func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { - return c.RunInDirTimeoutPipeline(-1, dir, stdout, stderr) -} - -// RunInDirBytes executes the command in given directory -// and returns stdout in []byte and error (combined with stderr). -func (c *Command) RunInDirBytes(dir string) ([]byte, error) { - return c.RunInDirTimeout(-1, dir) -} - -// RunInDir executes the command in given directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunInDir(dir string) (string, error) { - stdout, err := c.RunInDirTimeout(-1, dir) - if err != nil { - return "", err - } - return string(stdout), nil -} - -// RunTimeout executes the command in defualt working directory with given timeout, -// and returns stdout in string and error (combined with stderr). -func (c *Command) RunTimeout(timeout time.Duration) (string, error) { - stdout, err := c.RunInDirTimeout(timeout, "") - if err != nil { - return "", err - } - return string(stdout), nil -} - -// Run executes the command in defualt working directory -// and returns stdout in string and error (combined with stderr). -func (c *Command) Run() (string, error) { - return c.RunTimeout(-1) -} diff --git a/vendor/code.gitea.io/git/commit.go b/vendor/code.gitea.io/git/commit.go deleted file mode 100644 index 299a2381b65b6..0000000000000 --- a/vendor/code.gitea.io/git/commit.go +++ /dev/null @@ -1,276 +0,0 @@ -// 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 git - -import ( - "bufio" - "bytes" - "container/list" - "fmt" - "net/http" - "strconv" - "strings" -) - -// Commit represents a git commit. -type Commit struct { - Tree - ID SHA1 // The ID of this commit object - Author *Signature - Committer *Signature - CommitMessage string - Signature *CommitGPGSignature - - parents []SHA1 // SHA1 strings - submoduleCache *ObjectCache -} - -// CommitGPGSignature represents a git commit signature part. -type CommitGPGSignature struct { - Signature string - Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data -} - -// similar to https://github.com/git/git/blob/3bc53220cb2dcf709f7a027a3f526befd021d858/commit.c#L1128 -func newGPGSignatureFromCommitline(data []byte, signatureStart int) (*CommitGPGSignature, error) { - sig := new(CommitGPGSignature) - signatureEnd := bytes.LastIndex(data, []byte("-----END PGP SIGNATURE-----")) - if signatureEnd == -1 { - return nil, fmt.Errorf("end of commit signature not found") - } - sig.Signature = strings.Replace(string(data[signatureStart:signatureEnd+27]), "\n ", "\n", -1) - sig.Payload = string(data[:signatureStart-8]) + string(data[signatureEnd+27:]) - return sig, nil -} - -// Message returns the commit message. Same as retrieving CommitMessage directly. -func (c *Commit) Message() string { - return c.CommitMessage -} - -// Summary returns first line of commit message. -func (c *Commit) Summary() string { - return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0] -} - -// ParentID returns oid of n-th parent (0-based index). -// It returns nil if no such parent exists. -func (c *Commit) ParentID(n int) (SHA1, error) { - if n >= len(c.parents) { - return SHA1{}, ErrNotExist{"", ""} - } - return c.parents[n], nil -} - -// Parent returns n-th parent (0-based index) of the commit. -func (c *Commit) Parent(n int) (*Commit, error) { - id, err := c.ParentID(n) - if err != nil { - return nil, err - } - parent, err := c.repo.getCommit(id) - if err != nil { - return nil, err - } - return parent, nil -} - -// ParentCount returns number of parents of the commit. -// 0 if this is the root commit, otherwise 1,2, etc. -func (c *Commit) ParentCount() int { - return len(c.parents) -} - -func isImageFile(data []byte) (string, bool) { - contentType := http.DetectContentType(data) - if strings.Index(contentType, "image/") != -1 { - return contentType, true - } - return contentType, false -} - -// IsImageFile is a file image type -func (c *Commit) IsImageFile(name string) bool { - blob, err := c.GetBlobByPath(name) - if err != nil { - return false - } - - dataRc, err := blob.DataAsync() - if err != nil { - return false - } - defer dataRc.Close() - buf := make([]byte, 1024) - n, _ := dataRc.Read(buf) - buf = buf[:n] - _, isImage := isImageFile(buf) - return isImage -} - -// GetCommitByPath return the commit of relative path object. -func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) { - return c.repo.getCommitByPathWithID(c.ID, relpath) -} - -// AddChanges marks local changes to be ready for commit. -func AddChanges(repoPath string, all bool, files ...string) error { - cmd := NewCommand("add") - if all { - cmd.AddArguments("--all") - } - _, err := cmd.AddArguments(files...).RunInDir(repoPath) - return err -} - -// CommitChangesOptions the options when a commit created -type CommitChangesOptions struct { - Committer *Signature - Author *Signature - Message string -} - -// CommitChanges commits local changes with given committer, author and message. -// If author is nil, it will be the same as committer. -func CommitChanges(repoPath string, opts CommitChangesOptions) error { - cmd := NewCommand() - if opts.Committer != nil { - cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email) - } - cmd.AddArguments("commit") - - if opts.Author == nil { - opts.Author = opts.Committer - } - if opts.Author != nil { - cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)) - } - cmd.AddArguments("-m", opts.Message) - - _, err := cmd.RunInDir(repoPath) - // No stderr but exit status 1 means nothing to commit. - if err != nil && err.Error() == "exit status 1" { - return nil - } - return err -} - -func commitsCount(repoPath, revision, relpath string) (int64, error) { - var cmd *Command - cmd = NewCommand("rev-list", "--count") - cmd.AddArguments(revision) - if len(relpath) > 0 { - cmd.AddArguments("--", relpath) - } - - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return 0, err - } - - return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) -} - -// CommitsCount returns number of total commits of until given revision. -func CommitsCount(repoPath, revision string) (int64, error) { - return commitsCount(repoPath, revision, "") -} - -// CommitsCount returns number of total commits of until current revision. -func (c *Commit) CommitsCount() (int64, error) { - return CommitsCount(c.repo.Path, c.ID.String()) -} - -// CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize -func (c *Commit) CommitsByRange(page int) (*list.List, error) { - return c.repo.commitsByRange(c.ID, page) -} - -// CommitsBefore returns all the commits before current revision -func (c *Commit) CommitsBefore() (*list.List, error) { - return c.repo.getCommitsBefore(c.ID) -} - -// CommitsBeforeLimit returns num commits before current revision -func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) { - return c.repo.getCommitsBeforeLimit(c.ID, num) -} - -// CommitsBeforeUntil returns the commits between commitID to current revision -func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) { - endCommit, err := c.repo.GetCommit(commitID) - if err != nil { - return nil, err - } - return c.repo.CommitsBetween(c, endCommit) -} - -// SearchCommits returns the commits match the keyword before current revision -func (c *Commit) SearchCommits(keyword string, all bool) (*list.List, error) { - return c.repo.searchCommits(c.ID, keyword, all) -} - -// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision -func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) { - return c.repo.getFilesChanged(pastCommit, c.ID.String()) -} - -// GetSubModules get all the sub modules of current revision git tree -func (c *Commit) GetSubModules() (*ObjectCache, error) { - if c.submoduleCache != nil { - return c.submoduleCache, nil - } - - entry, err := c.GetTreeEntryByPath(".gitmodules") - if err != nil { - if _, ok := err.(ErrNotExist); ok { - return nil, nil - } - return nil, err - } - rd, err := entry.Blob().Data() - if err != nil { - return nil, err - } - - scanner := bufio.NewScanner(rd) - c.submoduleCache = newObjectCache() - var ismodule bool - var path string - for scanner.Scan() { - if strings.HasPrefix(scanner.Text(), "[submodule") { - ismodule = true - continue - } - if ismodule { - fields := strings.Split(scanner.Text(), "=") - k := strings.TrimSpace(fields[0]) - if k == "path" { - path = strings.TrimSpace(fields[1]) - } else if k == "url" { - c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])}) - ismodule = false - } - } - } - - return c.submoduleCache, nil -} - -// GetSubModule get the sub module according entryname -func (c *Commit) GetSubModule(entryname string) (*SubModule, error) { - modules, err := c.GetSubModules() - if err != nil { - return nil, err - } - - if modules != nil { - module, has := modules.Get(entryname) - if has { - return module.(*SubModule), nil - } - } - return nil, nil -} diff --git a/vendor/code.gitea.io/git/commit_archive.go b/vendor/code.gitea.io/git/commit_archive.go deleted file mode 100644 index e13825a96283b..0000000000000 --- a/vendor/code.gitea.io/git/commit_archive.go +++ /dev/null @@ -1,37 +0,0 @@ -// 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 git - -import ( - "fmt" - "path/filepath" - "strings" -) - -// ArchiveType archive types -type ArchiveType int - -const ( - // ZIP zip archive type - ZIP ArchiveType = iota + 1 - // TARGZ tar gz archive type - TARGZ -) - -// CreateArchive create archive content to the target path -func (c *Commit) CreateArchive(target string, archiveType ArchiveType) error { - var format string - switch archiveType { - case ZIP: - format = "zip" - case TARGZ: - format = "tar.gz" - default: - return fmt.Errorf("unknown format: %v", archiveType) - } - - _, err := NewCommand("archive", "--prefix="+filepath.Base(strings.TrimSuffix(c.repo.Path, ".git"))+"/", "--format="+format, "-o", target, c.ID.String()).RunInDir(c.repo.Path) - return err -} diff --git a/vendor/code.gitea.io/git/commit_info.go b/vendor/code.gitea.io/git/commit_info.go deleted file mode 100644 index 6b42b57c90133..0000000000000 --- a/vendor/code.gitea.io/git/commit_info.go +++ /dev/null @@ -1,319 +0,0 @@ -// 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 git - -import ( - "bufio" - "context" - "fmt" - "os/exec" - "path" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -const ( - // parameters for searching for commit infos. If the untargeted search has - // not found any entries in the past 5 commits, and 12 or fewer entries - // remain, then we'll just let the targeted-searching threads finish off, - // and stop the untargeted search to not interfere. - deferToTargetedSearchColdStreak = 5 - deferToTargetedSearchNumRemainingEntries = 12 -) - -// getCommitsInfoState shared state while getting commit info for entries -type getCommitsInfoState struct { - lock sync.Mutex - /* read-only fields, can be read without the mutex */ - // entries and entryPaths are read-only after initialization, so they can - // safely be read without the mutex - entries []*TreeEntry - // set of filepaths to get info for - entryPaths map[string]struct{} - treePath string - headCommit *Commit - - /* mutable fields, must hold mutex to read or write */ - // map from filepath to commit - commits map[string]*Commit - // set of filepaths that have been or are being searched for in a target search - targetedPaths map[string]struct{} -} - -func (state *getCommitsInfoState) numRemainingEntries() int { - state.lock.Lock() - defer state.lock.Unlock() - return len(state.entries) - len(state.commits) -} - -// getTargetEntryPath Returns the next path for a targeted-searching thread to -// search for, or returns the empty string if nothing left to search for -func (state *getCommitsInfoState) getTargetedEntryPath() string { - var targetedEntryPath string - state.lock.Lock() - defer state.lock.Unlock() - for _, entry := range state.entries { - entryPath := path.Join(state.treePath, entry.Name()) - if _, ok := state.commits[entryPath]; ok { - continue - } else if _, ok = state.targetedPaths[entryPath]; ok { - continue - } - targetedEntryPath = entryPath - state.targetedPaths[entryPath] = struct{}{} - break - } - return targetedEntryPath -} - -// repeatedly perform targeted searches for unpopulated entries -func targetedSearch(state *getCommitsInfoState, done chan error) { - for { - entryPath := state.getTargetedEntryPath() - if len(entryPath) == 0 { - done <- nil - return - } - command := NewCommand("rev-list", "-1", state.headCommit.ID.String(), "--", entryPath) - output, err := command.RunInDir(state.headCommit.repo.Path) - if err != nil { - done <- err - return - } - id, err := NewIDFromString(strings.TrimSpace(output)) - if err != nil { - done <- err - return - } - commit, err := state.headCommit.repo.getCommit(id) - if err != nil { - done <- err - return - } - state.update(entryPath, commit) - } -} - -func initGetCommitInfoState(entries Entries, headCommit *Commit, treePath string) *getCommitsInfoState { - entryPaths := make(map[string]struct{}, len(entries)) - for _, entry := range entries { - entryPaths[path.Join(treePath, entry.Name())] = struct{}{} - } - if treePath = path.Clean(treePath); treePath == "." { - treePath = "" - } - return &getCommitsInfoState{ - entries: entries, - entryPaths: entryPaths, - commits: make(map[string]*Commit, len(entries)), - targetedPaths: make(map[string]struct{}, len(entries)), - treePath: treePath, - headCommit: headCommit, - } -} - -// GetCommitsInfo gets information of all commits that are corresponding to these entries -func (tes Entries) GetCommitsInfo(commit *Commit, treePath string) ([][]interface{}, error) { - state := initGetCommitInfoState(tes, commit, treePath) - if err := getCommitsInfo(state); err != nil { - return nil, err - } - if len(state.commits) < len(state.entryPaths) { - return nil, fmt.Errorf("could not find commits for all entries") - } - - commitsInfo := make([][]interface{}, len(tes)) - for i, entry := range tes { - commit, ok := state.commits[path.Join(treePath, entry.Name())] - if !ok { - return nil, fmt.Errorf("could not find commit for %s", entry.Name()) - } - switch entry.Type { - case ObjectCommit: - subModuleURL := "" - if subModule, err := state.headCommit.GetSubModule(entry.Name()); err != nil { - return nil, err - } else if subModule != nil { - subModuleURL = subModule.URL - } - subModuleFile := NewSubModuleFile(commit, subModuleURL, entry.ID.String()) - commitsInfo[i] = []interface{}{entry, subModuleFile} - default: - commitsInfo[i] = []interface{}{entry, commit} - } - } - return commitsInfo, nil -} - -func (state *getCommitsInfoState) cleanEntryPath(rawEntryPath string) (string, error) { - if rawEntryPath[0] == '"' { - var err error - rawEntryPath, err = strconv.Unquote(rawEntryPath) - if err != nil { - return rawEntryPath, err - } - } - var entryNameStartIndex int - if len(state.treePath) > 0 { - entryNameStartIndex = len(state.treePath) + 1 - } - - if index := strings.IndexByte(rawEntryPath[entryNameStartIndex:], '/'); index >= 0 { - return rawEntryPath[:entryNameStartIndex+index], nil - } - return rawEntryPath, nil -} - -// update report that the given path was last modified by the given commit. -// Returns whether state.commits was updated -func (state *getCommitsInfoState) update(entryPath string, commit *Commit) bool { - if _, ok := state.entryPaths[entryPath]; !ok { - return false - } - - var updated bool - state.lock.Lock() - defer state.lock.Unlock() - if _, ok := state.commits[entryPath]; !ok { - state.commits[entryPath] = commit - updated = true - } - return updated -} - -const getCommitsInfoPretty = "--pretty=format:%H %ct %s" - -func getCommitsInfo(state *getCommitsInfoState) error { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) - defer cancel() - - args := []string{"log", state.headCommit.ID.String(), getCommitsInfoPretty, "--name-status", "-c"} - if len(state.treePath) > 0 { - args = append(args, "--", state.treePath) - } - cmd := exec.CommandContext(ctx, "git", args...) - cmd.Dir = state.headCommit.repo.Path - - readCloser, err := cmd.StdoutPipe() - if err != nil { - return err - } - - if err := cmd.Start(); err != nil { - return err - } - // it's okay to ignore the error returned by cmd.Wait(); we expect the - // subprocess to sometimes have a non-zero exit status, since we may - // prematurely close stdout, resulting in a broken pipe. - defer cmd.Wait() - - numThreads := runtime.NumCPU() - done := make(chan error, numThreads) - for i := 0; i < numThreads; i++ { - go targetedSearch(state, done) - } - - scanner := bufio.NewScanner(readCloser) - err = state.processGitLogOutput(scanner) - - // it is important that we close stdout here; if we do not close - // stdout, the subprocess will keep running, and the deffered call - // cmd.Wait() may block for a long time. - if closeErr := readCloser.Close(); closeErr != nil && err == nil { - err = closeErr - } - - for i := 0; i < numThreads; i++ { - doneErr := <-done - if doneErr != nil && err == nil { - err = doneErr - } - } - return err -} - -func (state *getCommitsInfoState) processGitLogOutput(scanner *bufio.Scanner) error { - // keep a local cache of seen paths to avoid acquiring a lock for paths - // we've already seen - seenPaths := make(map[string]struct{}, len(state.entryPaths)) - // number of consecutive commits without any finds - coldStreak := 0 - var commit *Commit - var err error - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 { // in-between commits - numRemainingEntries := state.numRemainingEntries() - if numRemainingEntries == 0 { - break - } - if coldStreak >= deferToTargetedSearchColdStreak && - numRemainingEntries <= deferToTargetedSearchNumRemainingEntries { - // stop this untargeted search, and let the targeted-search threads - // finish the work - break - } - continue - } - if line[0] >= 'A' && line[0] <= 'X' { // a file was changed by the current commit - // look for the last tab, since for copies (C) and renames (R) two - // filenames are printed: src, then dest - tabIndex := strings.LastIndexByte(line, '\t') - if tabIndex < 1 { - return fmt.Errorf("misformatted line: %s", line) - } - entryPath, err := state.cleanEntryPath(line[tabIndex+1:]) - if err != nil { - return err - } - if _, ok := seenPaths[entryPath]; !ok { - if state.update(entryPath, commit) { - coldStreak = 0 - } - seenPaths[entryPath] = struct{}{} - } - continue - } - - // a new commit - commit, err = parseCommitInfo(line) - if err != nil { - return err - } - coldStreak++ - } - return scanner.Err() -} - -// parseCommitInfo parse a commit from a line of `git log` output. Expects the -// line to be formatted according to getCommitsInfoPretty. -func parseCommitInfo(line string) (*Commit, error) { - if len(line) < 43 { - return nil, fmt.Errorf("invalid git output: %s", line) - } - ref, err := NewIDFromString(line[:40]) - if err != nil { - return nil, err - } - spaceIndex := strings.IndexByte(line[41:], ' ') - if spaceIndex < 0 { - return nil, fmt.Errorf("invalid git output: %s", line) - } - unixSeconds, err := strconv.Atoi(line[41 : 41+spaceIndex]) - if err != nil { - return nil, err - } - message := line[spaceIndex+42:] - return &Commit{ - ID: ref, - CommitMessage: message, - Committer: &Signature{ - When: time.Unix(int64(unixSeconds), 0), - }, - }, nil -} diff --git a/vendor/code.gitea.io/git/doc.go b/vendor/code.gitea.io/git/doc.go deleted file mode 100644 index 1941d285507b1..0000000000000 --- a/vendor/code.gitea.io/git/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// 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 git // import "code.gitea.io/git" diff --git a/vendor/code.gitea.io/git/error.go b/vendor/code.gitea.io/git/error.go deleted file mode 100644 index 1aae5a37a2891..0000000000000 --- a/vendor/code.gitea.io/git/error.go +++ /dev/null @@ -1,66 +0,0 @@ -// 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 git - -import ( - "fmt" - "time" -) - -// ErrExecTimeout error when exec timed out -type ErrExecTimeout struct { - Duration time.Duration -} - -// IsErrExecTimeout if some error is ErrExecTimeout -func IsErrExecTimeout(err error) bool { - _, ok := err.(ErrExecTimeout) - return ok -} - -func (err ErrExecTimeout) Error() string { - return fmt.Sprintf("execution is timeout [duration: %v]", err.Duration) -} - -// ErrNotExist commit not exist error -type ErrNotExist struct { - ID string - RelPath string -} - -// IsErrNotExist if some error is ErrNotExist -func IsErrNotExist(err error) bool { - _, ok := err.(ErrNotExist) - return ok -} - -func (err ErrNotExist) Error() string { - return fmt.Sprintf("object does not exist [id: %s, rel_path: %s]", err.ID, err.RelPath) -} - -// ErrBadLink entry.FollowLink error -type ErrBadLink struct { - Name string - Message string -} - -func (err ErrBadLink) Error() string { - return fmt.Sprintf("%s: %s", err.Name, err.Message) -} - -// ErrUnsupportedVersion error when required git version not matched -type ErrUnsupportedVersion struct { - Required string -} - -// IsErrUnsupportedVersion if some error is ErrUnsupportedVersion -func IsErrUnsupportedVersion(err error) bool { - _, ok := err.(ErrUnsupportedVersion) - return ok -} - -func (err ErrUnsupportedVersion) Error() string { - return fmt.Sprintf("Operation requires higher version [required: %s]", err.Required) -} diff --git a/vendor/code.gitea.io/git/git.go b/vendor/code.gitea.io/git/git.go deleted file mode 100644 index 150b80fb076b8..0000000000000 --- a/vendor/code.gitea.io/git/git.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2015 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 git - -import ( - "fmt" - "strings" - "time" - - "github.com/mcuadros/go-version" -) - -// Version return this package's current version -func Version() string { - return "0.4.2" -} - -var ( - // Debug enables verbose logging on everything. - // This should be false in case Gogs starts in SSH mode. - Debug = false - // Prefix the log prefix - Prefix = "[git-module] " - // GitVersionRequired is the minimum Git version required - GitVersionRequired = "1.7.2" -) - -func log(format string, args ...interface{}) { - if !Debug { - return - } - - fmt.Print(Prefix) - if len(args) == 0 { - fmt.Println(format) - } else { - fmt.Printf(format+"\n", args...) - } -} - -var gitVersion string - -// BinVersion returns current Git version from shell. -func BinVersion() (string, error) { - if len(gitVersion) > 0 { - return gitVersion, nil - } - - stdout, err := NewCommand("version").Run() - if err != nil { - return "", err - } - - fields := strings.Fields(stdout) - if len(fields) < 3 { - return "", fmt.Errorf("not enough output: %s", stdout) - } - - // Handle special case on Windows. - i := strings.Index(fields[2], "windows") - if i >= 1 { - gitVersion = fields[2][:i-1] - return gitVersion, nil - } - - gitVersion = fields[2] - return gitVersion, nil -} - -func init() { - gitVersion, err := BinVersion() - if err != nil { - panic(fmt.Sprintf("Git version missing: %v", err)) - } - if version.Compare(gitVersion, GitVersionRequired, "<") { - panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired)) - } -} - -// Fsck verifies the connectivity and validity of the objects in the database -func Fsck(repoPath string, timeout time.Duration, args ...string) error { - // Make sure timeout makes sense. - if timeout <= 0 { - timeout = -1 - } - _, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) - return err -} diff --git a/vendor/code.gitea.io/git/hook.go b/vendor/code.gitea.io/git/hook.go deleted file mode 100644 index afed623e6eacf..0000000000000 --- a/vendor/code.gitea.io/git/hook.go +++ /dev/null @@ -1,126 +0,0 @@ -// 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 git - -import ( - "errors" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - - "github.com/Unknwon/com" -) - -// hookNames is a list of Git server hooks' name that are supported. -var hookNames = []string{ - "pre-receive", - "update", - "post-receive", -} - -var ( - // ErrNotValidHook error when a git hook is not valid - ErrNotValidHook = errors.New("not a valid Git hook") -) - -// IsValidHookName returns true if given name is a valid Git hook. -func IsValidHookName(name string) bool { - for _, hn := range hookNames { - if hn == name { - return true - } - } - return false -} - -// Hook represents a Git hook. -type Hook struct { - name string - IsActive bool // Indicates whether repository has this hook. - Content string // Content of hook if it's active. - Sample string // Sample content from Git. - path string // Hook file path. -} - -// GetHook returns a Git hook by given name and repository. -func GetHook(repoPath, name string) (*Hook, error) { - if !IsValidHookName(name) { - return nil, ErrNotValidHook - } - h := &Hook{ - name: name, - path: path.Join(repoPath, "hooks", name+".d", name), - } - samplePath := filepath.Join(repoPath, "hooks", name+".sample") - if isFile(h.path) { - data, err := ioutil.ReadFile(h.path) - if err != nil { - return nil, err - } - h.IsActive = true - h.Content = string(data) - } else if isFile(samplePath) { - data, err := ioutil.ReadFile(samplePath) - if err != nil { - return nil, err - } - h.Sample = string(data) - } - return h, nil -} - -// Name return the name of the hook -func (h *Hook) Name() string { - return h.name -} - -// Update updates hook settings. -func (h *Hook) Update() error { - if len(strings.TrimSpace(h.Content)) == 0 { - if isExist(h.path) { - return os.Remove(h.path) - } - return nil - } - return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm) -} - -// ListHooks returns a list of Git hooks of given repository. -func ListHooks(repoPath string) (_ []*Hook, err error) { - if !isDir(path.Join(repoPath, "hooks")) { - return nil, errors.New("hooks path does not exist") - } - - hooks := make([]*Hook, len(hookNames)) - for i, name := range hookNames { - hooks[i], err = GetHook(repoPath, name) - if err != nil { - return nil, err - } - } - return hooks, nil -} - -const ( - // HookPathUpdate hook update path - HookPathUpdate = "hooks/update" -) - -// SetUpdateHook writes given content to update hook of the reposiotry. -func SetUpdateHook(repoPath, content string) (err error) { - log("Setting update hook: %s", repoPath) - hookPath := path.Join(repoPath, HookPathUpdate) - if com.IsExist(hookPath) { - err = os.Remove(hookPath) - } else { - err = os.MkdirAll(path.Dir(hookPath), os.ModePerm) - } - if err != nil { - return err - } - return ioutil.WriteFile(hookPath, []byte(content), 0777) -} diff --git a/vendor/code.gitea.io/git/parse.go b/vendor/code.gitea.io/git/parse.go deleted file mode 100644 index 5c964f16ee5f7..0000000000000 --- a/vendor/code.gitea.io/git/parse.go +++ /dev/null @@ -1,81 +0,0 @@ -// 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 git - -import ( - "bytes" - "fmt" - "strconv" -) - -// ParseTreeEntries parses the output of a `git ls-tree` command. -func ParseTreeEntries(data []byte) ([]*TreeEntry, error) { - return parseTreeEntries(data, nil) -} - -func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) { - entries := make([]*TreeEntry, 0, 10) - for pos := 0; pos < len(data); { - // expect line to be of the form " \t" - entry := new(TreeEntry) - entry.ptree = ptree - if pos+6 > len(data) { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - switch string(data[pos : pos+6]) { - case "100644": - entry.mode = EntryModeBlob - entry.Type = ObjectBlob - pos += 12 // skip over "100644 blob " - case "100755": - entry.mode = EntryModeExec - entry.Type = ObjectBlob - pos += 12 // skip over "100755 blob " - case "120000": - entry.mode = EntryModeSymlink - entry.Type = ObjectBlob - pos += 12 // skip over "120000 blob " - case "160000": - entry.mode = EntryModeCommit - entry.Type = ObjectCommit - pos += 14 // skip over "160000 object " - case "040000": - entry.mode = EntryModeTree - entry.Type = ObjectTree - pos += 12 // skip over "040000 tree " - default: - return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6])) - } - - if pos+40 > len(data) { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - id, err := NewIDFromString(string(data[pos : pos+40])) - if err != nil { - return nil, fmt.Errorf("Invalid ls-tree output: %v", err) - } - entry.ID = id - pos += 41 // skip over sha and trailing space - - end := pos + bytes.IndexByte(data[pos:], '\n') - if end < pos { - return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) - } - - // In case entry name is surrounded by double quotes(it happens only in git-shell). - if data[pos] == '"' { - entry.name, err = strconv.Unquote(string(data[pos:end])) - if err != nil { - return nil, fmt.Errorf("Invalid ls-tree output: %v", err) - } - } else { - entry.name = string(data[pos:end]) - } - - pos = end + 1 - entries = append(entries, entry) - } - return entries, nil -} diff --git a/vendor/code.gitea.io/git/repo.go b/vendor/code.gitea.io/git/repo.go deleted file mode 100644 index 4306730920eb2..0000000000000 --- a/vendor/code.gitea.io/git/repo.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2015 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 git - -import ( - "bytes" - "container/list" - "errors" - "os" - "path" - "path/filepath" - "strings" - "time" - - "github.com/Unknwon/com" -) - -// Repository represents a Git repository. -type Repository struct { - Path string - - commitCache *ObjectCache - tagCache *ObjectCache -} - -const prettyLogFormat = `--pretty=format:%H` - -func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) { - l := list.New() - if len(logs) == 0 { - return l, nil - } - - parts := bytes.Split(logs, []byte{'\n'}) - - for _, commitID := range parts { - commit, err := repo.GetCommit(string(commitID)) - if err != nil { - return nil, err - } - l.PushBack(commit) - } - - return l, nil -} - -// IsRepoURLAccessible checks if given repository URL is accessible. -func IsRepoURLAccessible(url string) bool { - _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run() - if err != nil { - return false - } - return true -} - -// InitRepository initializes a new Git repository. -func InitRepository(repoPath string, bare bool) error { - os.MkdirAll(repoPath, os.ModePerm) - - cmd := NewCommand("init") - if bare { - cmd.AddArguments("--bare") - } - _, err := cmd.RunInDir(repoPath) - return err -} - -// OpenRepository opens the repository at the given path. -func OpenRepository(repoPath string) (*Repository, error) { - repoPath, err := filepath.Abs(repoPath) - if err != nil { - return nil, err - } else if !isDir(repoPath) { - return nil, errors.New("no such file or directory") - } - - return &Repository{ - Path: repoPath, - commitCache: newObjectCache(), - tagCache: newObjectCache(), - }, nil -} - -// CloneRepoOptions options when clone a repository -type CloneRepoOptions struct { - Timeout time.Duration - Mirror bool - Bare bool - Quiet bool - Branch string -} - -// Clone clones original repository to target path. -func Clone(from, to string, opts CloneRepoOptions) (err error) { - toDir := path.Dir(to) - if err = os.MkdirAll(toDir, os.ModePerm); err != nil { - return err - } - - cmd := NewCommand("clone") - if opts.Mirror { - cmd.AddArguments("--mirror") - } - if opts.Bare { - cmd.AddArguments("--bare") - } - if opts.Quiet { - cmd.AddArguments("--quiet") - } - if len(opts.Branch) > 0 { - cmd.AddArguments("-b", opts.Branch) - } - cmd.AddArguments(from, to) - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - _, err = cmd.RunTimeout(opts.Timeout) - return err -} - -// PullRemoteOptions options when pull from remote -type PullRemoteOptions struct { - Timeout time.Duration - All bool - Rebase bool - Remote string - Branch string -} - -// Pull pulls changes from remotes. -func Pull(repoPath string, opts PullRemoteOptions) error { - cmd := NewCommand("pull") - if opts.Rebase { - cmd.AddArguments("--rebase") - } - if opts.All { - cmd.AddArguments("--all") - } else { - cmd.AddArguments(opts.Remote) - cmd.AddArguments(opts.Branch) - } - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) - return err -} - -// PushOptions options when push to remote -type PushOptions struct { - Remote string - Branch string - Force bool -} - -// Push pushs local commits to given remote branch. -func Push(repoPath string, opts PushOptions) error { - cmd := NewCommand("push") - if opts.Force { - cmd.AddArguments("-f") - } - cmd.AddArguments(opts.Remote, opts.Branch) - _, err := cmd.RunInDir(repoPath) - return err -} - -// CheckoutOptions options when heck out some branch -type CheckoutOptions struct { - Timeout time.Duration - Branch string - OldBranch string -} - -// Checkout checkouts a branch -func Checkout(repoPath string, opts CheckoutOptions) error { - cmd := NewCommand("checkout") - if len(opts.OldBranch) > 0 { - cmd.AddArguments("-b") - } - - if opts.Timeout <= 0 { - opts.Timeout = -1 - } - - cmd.AddArguments(opts.Branch) - - if len(opts.OldBranch) > 0 { - cmd.AddArguments(opts.OldBranch) - } - - _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) - return err -} - -// ResetHEAD resets HEAD to given revision or head of branch. -func ResetHEAD(repoPath string, hard bool, revision string) error { - cmd := NewCommand("reset") - if hard { - cmd.AddArguments("--hard") - } - _, err := cmd.AddArguments(revision).RunInDir(repoPath) - return err -} - -// MoveFile moves a file to another file or directory. -func MoveFile(repoPath, oldTreeName, newTreeName string) error { - _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath) - return err -} - -// CountObject represents repository count objects report -type CountObject struct { - Count int64 - Size int64 - InPack int64 - Packs int64 - SizePack int64 - PrunePack int64 - Garbage int64 - SizeGarbage int64 -} - -const ( - statCount = "count: " - statSize = "size: " - statInpack = "in-pack: " - statPacks = "packs: " - statSizePack = "size-pack: " - statPrunePackage = "prune-package: " - statGarbage = "garbage: " - statSizeGarbage = "size-garbage: " -) - -// GetRepoSize returns disk consumption for repo in path -func GetRepoSize(repoPath string) (*CountObject, error) { - cmd := NewCommand("count-objects", "-v") - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return nil, err - } - - return parseSize(stdout), nil -} - -// parseSize parses the output from count-objects and return a CountObject -func parseSize(objects string) *CountObject { - repoSize := new(CountObject) - for _, line := range strings.Split(objects, "\n") { - switch { - case strings.HasPrefix(line, statCount): - repoSize.Count = com.StrTo(line[7:]).MustInt64() - case strings.HasPrefix(line, statSize): - repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024 - case strings.HasPrefix(line, statInpack): - repoSize.InPack = com.StrTo(line[9:]).MustInt64() - case strings.HasPrefix(line, statPacks): - repoSize.Packs = com.StrTo(line[7:]).MustInt64() - case strings.HasPrefix(line, statSizePack): - repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024 - case strings.HasPrefix(line, statPrunePackage): - repoSize.PrunePack = com.StrTo(line[16:]).MustInt64() - case strings.HasPrefix(line, statGarbage): - repoSize.Garbage = com.StrTo(line[9:]).MustInt64() - case strings.HasPrefix(line, statSizeGarbage): - repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024 - } - } - return repoSize -} - -// GetLatestCommitTime returns time for latest commit in repository (across all branches) -func GetLatestCommitTime(repoPath string) (time.Time, error) { - cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)") - stdout, err := cmd.RunInDir(repoPath) - if err != nil { - return time.Time{}, err - } - commitTime := strings.TrimSpace(stdout) - return time.Parse(GitTimeLayout, commitTime) -} diff --git a/vendor/code.gitea.io/git/repo_blame.go b/vendor/code.gitea.io/git/repo_blame.go deleted file mode 100644 index 80ec50e4723cf..0000000000000 --- a/vendor/code.gitea.io/git/repo_blame.go +++ /dev/null @@ -1,24 +0,0 @@ -// 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 git - -import "fmt" - -// FileBlame return the Blame object of file -func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { - return NewCommand("blame", "--root", "--", file).RunInDirBytes(path) -} - -// LineBlame returns the latest commit at the given line -func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { - res, err := NewCommand("blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) - if err != nil { - return nil, err - } - if len(res) < 40 { - return nil, fmt.Errorf("invalid result of blame: %s", res) - } - return repo.GetCommit(string(res[:40])) -} diff --git a/vendor/code.gitea.io/git/repo_branch.go b/vendor/code.gitea.io/git/repo_branch.go deleted file mode 100644 index 3b50eece14a31..0000000000000 --- a/vendor/code.gitea.io/git/repo_branch.go +++ /dev/null @@ -1,123 +0,0 @@ -// 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 git - -import ( - "fmt" - "strings" -) - -// BranchPrefix base dir of the branch information file store on git -const BranchPrefix = "refs/heads/" - -// IsReferenceExist returns true if given reference exists in the repository. -func IsReferenceExist(repoPath, name string) bool { - _, err := NewCommand("show-ref", "--verify", name).RunInDir(repoPath) - return err == nil -} - -// IsBranchExist returns true if given branch exists in the repository. -func IsBranchExist(repoPath, name string) bool { - return IsReferenceExist(repoPath, BranchPrefix+name) -} - -// IsBranchExist returns true if given branch exists in current repository. -func (repo *Repository) IsBranchExist(name string) bool { - return IsBranchExist(repo.Path, name) -} - -// Branch represents a Git branch. -type Branch struct { - Name string - Path string -} - -// GetHEADBranch returns corresponding branch of HEAD. -func (repo *Repository) GetHEADBranch() (*Branch, error) { - stdout, err := NewCommand("symbolic-ref", "HEAD").RunInDir(repo.Path) - if err != nil { - return nil, err - } - stdout = strings.TrimSpace(stdout) - - if !strings.HasPrefix(stdout, BranchPrefix) { - return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) - } - - return &Branch{ - Name: stdout[len(BranchPrefix):], - Path: stdout, - }, nil -} - -// SetDefaultBranch sets default branch of repository. -func (repo *Repository) SetDefaultBranch(name string) error { - _, err := NewCommand("symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) - return err -} - -// GetBranches returns all branches of the repository. -func (repo *Repository) GetBranches() ([]string, error) { - stdout, err := NewCommand("for-each-ref", "--format=%(refname)", BranchPrefix).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - refs := strings.Split(stdout, "\n") - branches := make([]string, len(refs)-1) - for i, ref := range refs[:len(refs)-1] { - branches[i] = strings.TrimPrefix(ref, BranchPrefix) - } - return branches, nil -} - -// DeleteBranchOptions Option(s) for delete branch -type DeleteBranchOptions struct { - Force bool -} - -// DeleteBranch delete a branch by name on repository. -func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { - cmd := NewCommand("branch") - - if opts.Force { - cmd.AddArguments("-D") - } else { - cmd.AddArguments("-d") - } - - cmd.AddArguments(name) - _, err := cmd.RunInDir(repo.Path) - - return err -} - -// CreateBranch create a new branch -func (repo *Repository) CreateBranch(branch, newBranch string) error { - cmd := NewCommand("branch") - cmd.AddArguments(branch, newBranch) - - _, err := cmd.RunInDir(repo.Path) - - return err -} - -// AddRemote adds a new remote to repository. -func (repo *Repository) AddRemote(name, url string, fetch bool) error { - cmd := NewCommand("remote", "add") - if fetch { - cmd.AddArguments("-f") - } - cmd.AddArguments(name, url) - - _, err := cmd.RunInDir(repo.Path) - return err -} - -// RemoveRemote removes a remote from repository. -func (repo *Repository) RemoveRemote(name string) error { - _, err := NewCommand("remote", "remove", name).RunInDir(repo.Path) - return err -} diff --git a/vendor/code.gitea.io/git/repo_commit.go b/vendor/code.gitea.io/git/repo_commit.go deleted file mode 100644 index 1acdfffb34738..0000000000000 --- a/vendor/code.gitea.io/git/repo_commit.go +++ /dev/null @@ -1,352 +0,0 @@ -// 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 git - -import ( - "bytes" - "container/list" - "strconv" - "strings" - - "github.com/mcuadros/go-version" -) - -// GetRefCommitID returns the last commit ID string of given reference (branch or tag). -func (repo *Repository) GetRefCommitID(name string) (string, error) { - stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path) - if err != nil { - if strings.Contains(err.Error(), "not a valid ref") { - return "", ErrNotExist{name, ""} - } - return "", err - } - return strings.Split(stdout, " ")[0], nil -} - -// GetBranchCommitID returns last commit ID string of given branch. -func (repo *Repository) GetBranchCommitID(name string) (string, error) { - return repo.GetRefCommitID(BranchPrefix + name) -} - -// GetTagCommitID returns last commit ID string of given tag. -func (repo *Repository) GetTagCommitID(name string) (string, error) { - return repo.GetRefCommitID(TagPrefix + name) -} - -// parseCommitData parses commit information from the (uncompressed) raw -// data from the commit object. -// \n\n separate headers from message -func parseCommitData(data []byte) (*Commit, error) { - commit := new(Commit) - commit.parents = make([]SHA1, 0, 1) - // we now have the contents of the commit object. Let's investigate... - nextline := 0 -l: - for { - eol := bytes.IndexByte(data[nextline:], '\n') - switch { - case eol > 0: - line := data[nextline : nextline+eol] - spacepos := bytes.IndexByte(line, ' ') - reftype := line[:spacepos] - switch string(reftype) { - case "tree", "object": - id, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - commit.Tree.ID = id - case "parent": - // A commit can have one or more parents - oid, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - commit.parents = append(commit.parents, oid) - case "author", "tagger": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - commit.Author = sig - case "committer": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - commit.Committer = sig - case "gpgsig": - sig, err := newGPGSignatureFromCommitline(data, nextline+spacepos+1) - if err != nil { - return nil, err - } - commit.Signature = sig - } - nextline += eol + 1 - case eol == 0: - commit.CommitMessage = string(data[nextline+1:]) - break l - default: - break l - } - } - return commit, nil -} - -func (repo *Repository) getCommit(id SHA1) (*Commit, error) { - c, ok := repo.commitCache.Get(id.String()) - if ok { - log("Hit cache: %s", id) - return c.(*Commit), nil - } - - data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) - if err != nil { - if strings.Contains(err.Error(), "fatal: Not a valid object name") { - return nil, ErrNotExist{id.String(), ""} - } - return nil, err - } - - commit, err := parseCommitData(data) - if err != nil { - return nil, err - } - commit.repo = repo - commit.ID = id - - repo.commitCache.Set(id.String(), commit) - return commit, nil -} - -// GetCommit returns commit object of by ID string. -func (repo *Repository) GetCommit(commitID string) (*Commit, error) { - if len(commitID) != 40 { - var err error - commitID, err = NewCommand("rev-parse", commitID).RunInDir(repo.Path) - if err != nil { - return nil, err - } - } - id, err := NewIDFromString(commitID) - if err != nil { - return nil, err - } - - return repo.getCommit(id) -} - -// GetBranchCommit returns the last commit of given branch. -func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { - commitID, err := repo.GetBranchCommitID(name) - if err != nil { - return nil, err - } - return repo.GetCommit(commitID) -} - -// GetTagCommit get the commit of the specific tag via name -func (repo *Repository) GetTagCommit(name string) (*Commit, error) { - commitID, err := repo.GetTagCommitID(name) - if err != nil { - return nil, err - } - return repo.GetCommit(commitID) -} - -func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) { - // File name starts with ':' must be escaped. - if relpath[0] == ':' { - relpath = `\` + relpath - } - - stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - id, err = NewIDFromString(stdout) - if err != nil { - return nil, err - } - - return repo.getCommit(id) -} - -// GetCommitByPath returns the last commit of relative path. -func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { - stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - commits, err := repo.parsePrettyFormatLogToList(stdout) - if err != nil { - return nil, err - } - return commits.Front().Value.(*Commit), nil -} - -// CommitsRangeSize the default commits range size -var CommitsRangeSize = 50 - -func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) { - stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize), - "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -func (repo *Repository) searchCommits(id SHA1, keyword string, all bool) (*list.List, error) { - cmd := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, prettyLogFormat) - if all { - cmd.AddArguments("--all") - } - stdout, err := cmd.RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) { - stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return strings.Split(string(stdout), "\n"), nil -} - -// FileCommitsCount return the number of files at a revison -func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) { - return commitsCount(repo.Path, revision, file) -} - -// CommitsByFileAndRange return the commits accroding revison file and the page -func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) { - stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50), - "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(stdout) -} - -// FilesCountBetween return the number of files changed between two commits -func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { - stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) - if err != nil { - return 0, err - } - return len(strings.Split(stdout, "\n")) - 1, nil -} - -// CommitsBetween returns a list that contains commits between [last, before). -func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { - stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) -} - -// CommitsBetweenIDs return commits between twoe commits -func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) { - lastCommit, err := repo.GetCommit(last) - if err != nil { - return nil, err - } - beforeCommit, err := repo.GetCommit(before) - if err != nil { - return nil, err - } - return repo.CommitsBetween(lastCommit, beforeCommit) -} - -// CommitsCountBetween return numbers of commits between two commits -func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) { - return commitsCount(repo.Path, start+"..."+end, "") -} - -// commitsBefore the limit is depth, not total number of returned commits. -func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) { - cmd := NewCommand("log") - if limit > 0 { - cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String()) - } else { - cmd.AddArguments(prettyLogFormat, id.String()) - } - - stdout, err := cmd.RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) - if err != nil { - return nil, err - } - - commits := list.New() - for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() { - commit := logEntry.Value.(*Commit) - branches, err := repo.getBranches(commit, 2) - if err != nil { - return nil, err - } - - if len(branches) > 1 { - break - } - - commits.PushBack(commit) - } - - return commits, nil -} - -func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) { - return repo.commitsBefore(id, 0) -} - -func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) { - return repo.commitsBefore(id, num) -} - -func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { - if version.Compare(gitVersion, "2.7.0", ">=") { - stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - branches := strings.Fields(stdout) - return branches, nil - } - - stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - refs := strings.Split(stdout, "\n") - - var max int - if len(refs) > limit { - max = limit - } else { - max = len(refs) - 1 - } - - branches := make([]string, max) - for i, ref := range refs[:max] { - parts := strings.Fields(ref) - - branches[i] = parts[len(parts)-1] - } - return branches, nil -} diff --git a/vendor/code.gitea.io/git/repo_hook.go b/vendor/code.gitea.io/git/repo_hook.go deleted file mode 100644 index 49f4d09fb685b..0000000000000 --- a/vendor/code.gitea.io/git/repo_hook.go +++ /dev/null @@ -1,15 +0,0 @@ -// 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 git - -// GetHook get one hook accroding the name on a repository -func (repo *Repository) GetHook(name string) (*Hook, error) { - return GetHook(repo.Path, name) -} - -// Hooks get all the hooks on the repository -func (repo *Repository) Hooks() ([]*Hook, error) { - return ListHooks(repo.Path) -} diff --git a/vendor/code.gitea.io/git/repo_object.go b/vendor/code.gitea.io/git/repo_object.go deleted file mode 100644 index 3be8400d22210..0000000000000 --- a/vendor/code.gitea.io/git/repo_object.go +++ /dev/null @@ -1,19 +0,0 @@ -// 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 git - -// ObjectType git object type -type ObjectType string - -const ( - // ObjectCommit commit object type - ObjectCommit ObjectType = "commit" - // ObjectTree tree object type - ObjectTree ObjectType = "tree" - // ObjectBlob blob object type - ObjectBlob ObjectType = "blob" - // ObjectTag tag object type - ObjectTag ObjectType = "tag" -) diff --git a/vendor/code.gitea.io/git/repo_pull.go b/vendor/code.gitea.io/git/repo_pull.go deleted file mode 100644 index c6d97a6fd167d..0000000000000 --- a/vendor/code.gitea.io/git/repo_pull.go +++ /dev/null @@ -1,89 +0,0 @@ -// 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 git - -import ( - "bytes" - "container/list" - "fmt" - "io" - "strconv" - "strings" - "time" -) - -// PullRequestInfo represents needed information for a pull request. -type PullRequestInfo struct { - MergeBase string - Commits *list.List - NumFiles int -} - -// GetMergeBase checks and returns merge base of two branches. -func (repo *Repository) GetMergeBase(base, head string) (string, error) { - stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path) - return strings.TrimSpace(stdout), err -} - -// GetPullRequestInfo generates and returns pull request information -// between base and head branches of repositories. -func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) { - var remoteBranch string - - // We don't need a temporary remote for same repository. - if repo.Path != basePath { - // Add a temporary remote - tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) - if err = repo.AddRemote(tmpRemote, basePath, true); err != nil { - return nil, fmt.Errorf("AddRemote: %v", err) - } - defer repo.RemoveRemote(tmpRemote) - - remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch - } else { - remoteBranch = baseBranch - } - - prInfo := new(PullRequestInfo) - prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch) - if err != nil { - return nil, fmt.Errorf("GetMergeBase: %v", err) - } - - logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs) - if err != nil { - return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err) - } - - // Count number of changed files. - stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path) - if err != nil { - return nil, err - } - prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1 - - return prInfo, nil -} - -// GetPatch generates and returns patch data between given revisions. -func (repo *Repository) GetPatch(base, head string) ([]byte, error) { - return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path) -} - -// GetFormatPatch generates and returns format-patch data between given revisions. -func (repo *Repository) GetFormatPatch(base, head string) (io.Reader, error) { - stdout := new(bytes.Buffer) - stderr := new(bytes.Buffer) - - if err := NewCommand("format-patch", "--binary", "--stdout", base+"..."+head). - RunInDirPipeline(repo.Path, stdout, stderr); err != nil { - return nil, concatenateError(err, stderr.String()) - } - return stdout, nil -} diff --git a/vendor/code.gitea.io/git/repo_tag.go b/vendor/code.gitea.io/git/repo_tag.go deleted file mode 100644 index 11f1f3da73af9..0000000000000 --- a/vendor/code.gitea.io/git/repo_tag.go +++ /dev/null @@ -1,157 +0,0 @@ -// 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 git - -import ( - "strings" - - "github.com/mcuadros/go-version" -) - -// TagPrefix tags prefix path on the repository -const TagPrefix = "refs/tags/" - -// IsTagExist returns true if given tag exists in the repository. -func IsTagExist(repoPath, name string) bool { - return IsReferenceExist(repoPath, TagPrefix+name) -} - -// IsTagExist returns true if given tag exists in the repository. -func (repo *Repository) IsTagExist(name string) bool { - return IsTagExist(repo.Path, name) -} - -// CreateTag create one tag in the repository -func (repo *Repository) CreateTag(name, revision string) error { - _, err := NewCommand("tag", name, revision).RunInDir(repo.Path) - return err -} - -func (repo *Repository) getTag(id SHA1) (*Tag, error) { - t, ok := repo.tagCache.Get(id.String()) - if ok { - log("Hit cache: %s", id) - return t.(*Tag), nil - } - - // Get tag type - tp, err := NewCommand("cat-file", "-t", id.String()).RunInDir(repo.Path) - if err != nil { - return nil, err - } - tp = strings.TrimSpace(tp) - - // Tag is a commit. - if ObjectType(tp) == ObjectCommit { - tag := &Tag{ - ID: id, - Object: id, - Type: string(ObjectCommit), - repo: repo, - } - - repo.tagCache.Set(id.String(), tag) - return tag, nil - } - - // Tag with message. - data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) - if err != nil { - return nil, err - } - - tag, err := parseTagData(data) - if err != nil { - return nil, err - } - - tag.ID = id - tag.repo = repo - - repo.tagCache.Set(id.String(), tag) - return tag, nil -} - -// GetTag returns a Git tag by given name. -func (repo *Repository) GetTag(name string) (*Tag, error) { - stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path) - if err != nil { - return nil, err - } - - id, err := NewIDFromString(strings.Split(stdout, " ")[0]) - if err != nil { - return nil, err - } - - tag, err := repo.getTag(id) - if err != nil { - return nil, err - } - tag.Name = name - return tag, nil -} - -// GetTagInfos returns all tag infos of the repository. -func (repo *Repository) GetTagInfos() ([]*Tag, error) { - // TODO this a slow implementation, makes one git command per tag - stdout, err := NewCommand("tag").RunInDir(repo.Path) - if err != nil { - return nil, err - } - - tagNames := strings.Split(stdout, "\n") - var tags []*Tag - for _, tagName := range tagNames { - tagName = strings.TrimSpace(tagName) - if len(tagName) == 0 { - continue - } - commitID, err := NewCommand("rev-parse", tagName).RunInDir(repo.Path) - if err != nil { - return nil, err - } - commit, err := repo.GetCommit(commitID) - if err != nil { - return nil, err - } - tags = append(tags, &Tag{ - Name: tagName, - Message: commit.Message(), - Object: commit.ID, - Tagger: commit.Author, - }) - } - sortTagsByTime(tags) - return tags, nil -} - -// GetTags returns all tags of the repository. -func (repo *Repository) GetTags() ([]string, error) { - cmd := NewCommand("tag", "-l") - if version.Compare(gitVersion, "2.0.0", ">=") { - cmd.AddArguments("--sort=-v:refname") - } - - stdout, err := cmd.RunInDir(repo.Path) - if err != nil { - return nil, err - } - - tags := strings.Split(stdout, "\n") - tags = tags[:len(tags)-1] - - if version.Compare(gitVersion, "2.0.0", "<") { - version.Sort(tags) - - // Reverse order - for i := 0; i < len(tags)/2; i++ { - j := len(tags) - i - 1 - tags[i], tags[j] = tags[j], tags[i] - } - } - - return tags, nil -} diff --git a/vendor/code.gitea.io/git/repo_tree.go b/vendor/code.gitea.io/git/repo_tree.go deleted file mode 100644 index 6e3843f7e5389..0000000000000 --- a/vendor/code.gitea.io/git/repo_tree.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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 git - -func (repo *Repository) getTree(id SHA1) (*Tree, error) { - treePath := filepathFromSHA1(repo.Path, id.String()) - if isFile(treePath) { - _, err := NewCommand("ls-tree", id.String()).RunInDir(repo.Path) - if err != nil { - return nil, ErrNotExist{id.String(), ""} - } - } - - return NewTree(repo, id), nil -} - -// GetTree find the tree object in the repository. -func (repo *Repository) GetTree(idStr string) (*Tree, error) { - id, err := NewIDFromString(idStr) - if err != nil { - return nil, err - } - return repo.getTree(id) -} diff --git a/vendor/code.gitea.io/git/sha1.go b/vendor/code.gitea.io/git/sha1.go deleted file mode 100644 index 6c9d53949dff9..0000000000000 --- a/vendor/code.gitea.io/git/sha1.go +++ /dev/null @@ -1,76 +0,0 @@ -// 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 git - -import ( - "bytes" - "encoding/hex" - "fmt" - "strings" -) - -// EmptySHA defines empty git SHA -const EmptySHA = "0000000000000000000000000000000000000000" - -// SHA1 a git commit name -type SHA1 [20]byte - -// Equal returns true if s has the same SHA1 as caller. -// Support 40-length-string, []byte, SHA1. -func (id SHA1) Equal(s2 interface{}) bool { - switch v := s2.(type) { - case string: - if len(v) != 40 { - return false - } - return v == id.String() - case []byte: - return bytes.Equal(v, id[:]) - case SHA1: - return v == id - default: - return false - } -} - -// String returns string (hex) representation of the Oid. -func (id SHA1) String() string { - return hex.EncodeToString(id[:]) -} - -// MustID always creates a new SHA1 from a [20]byte array with no validation of input. -func MustID(b []byte) SHA1 { - var id SHA1 - copy(id[:], b) - return id -} - -// NewID creates a new SHA1 from a [20]byte array. -func NewID(b []byte) (SHA1, error) { - if len(b) != 20 { - return SHA1{}, fmt.Errorf("Length must be 20: %v", b) - } - return MustID(b), nil -} - -// MustIDFromString always creates a new sha from a ID with no validation of input. -func MustIDFromString(s string) SHA1 { - b, _ := hex.DecodeString(s) - return MustID(b) -} - -// NewIDFromString creates a new SHA1 from a ID string of length 40. -func NewIDFromString(s string) (SHA1, error) { - var id SHA1 - s = strings.TrimSpace(s) - if len(s) != 40 { - return id, fmt.Errorf("Length must be 40: %s", s) - } - b, err := hex.DecodeString(s) - if err != nil { - return id, err - } - return NewID(b) -} diff --git a/vendor/code.gitea.io/git/signature.go b/vendor/code.gitea.io/git/signature.go deleted file mode 100644 index e6ab247fd73fa..0000000000000 --- a/vendor/code.gitea.io/git/signature.go +++ /dev/null @@ -1,58 +0,0 @@ -// 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 git - -import ( - "bytes" - "strconv" - "time" -) - -// Signature represents the Author or Committer information. -type Signature struct { - Email string - Name string - When time.Time -} - -const ( - // GitTimeLayout is the (default) time layout used by git. - GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700" -) - -// Helper to get a signature from the commit line, which looks like these: -// author Patrick Gundlach 1378823654 +0200 -// author Patrick Gundlach Thu, 07 Apr 2005 22:13:13 +0200 -// but without the "author " at the beginning (this method should) -// be used for author and committer. -// -// FIXME: include timezone for timestamp! -func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { - sig := new(Signature) - emailStart := bytes.IndexByte(line, '<') - sig.Name = string(line[:emailStart-1]) - emailEnd := bytes.IndexByte(line, '>') - sig.Email = string(line[emailStart+1 : emailEnd]) - - // Check date format. - if len(line) > emailEnd+2 { - firstChar := line[emailEnd+2] - if firstChar >= 48 && firstChar <= 57 { - timestop := bytes.IndexByte(line[emailEnd+2:], ' ') - timestring := string(line[emailEnd+2 : emailEnd+2+timestop]) - seconds, _ := strconv.ParseInt(timestring, 10, 64) - sig.When = time.Unix(seconds, 0) - } else { - sig.When, err = time.Parse(GitTimeLayout, string(line[emailEnd+2:])) - if err != nil { - return nil, err - } - } - } else { - // Fall back to unix 0 time - sig.When = time.Unix(0, 0) - } - return sig, nil -} diff --git a/vendor/code.gitea.io/git/submodule.go b/vendor/code.gitea.io/git/submodule.go deleted file mode 100644 index a0fe7b4a5691c..0000000000000 --- a/vendor/code.gitea.io/git/submodule.go +++ /dev/null @@ -1,79 +0,0 @@ -// 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 git - -import "strings" - -// SubModule submodule is a reference on git repository -type SubModule struct { - Name string - URL string -} - -// SubModuleFile represents a file with submodule type. -type SubModuleFile struct { - *Commit - - refURL string - refID string -} - -// NewSubModuleFile create a new submodule file -func NewSubModuleFile(c *Commit, refURL, refID string) *SubModuleFile { - return &SubModuleFile{ - Commit: c, - refURL: refURL, - refID: refID, - } -} - -// RefURL guesses and returns reference URL. -func (sf *SubModuleFile) RefURL(urlPrefix string, parentPath string) string { - if sf.refURL == "" { - return "" - } - - url := strings.TrimSuffix(sf.refURL, ".git") - - // git://xxx/user/repo - if strings.HasPrefix(url, "git://") { - return "http://" + strings.TrimPrefix(url, "git://") - } - - // http[s]://xxx/user/repo - if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { - return url - } - - // Relative url prefix check (according to git submodule documentation) - if strings.HasPrefix(url, "./") || strings.HasPrefix(url, "../") { - // ...construct and return correct submodule url here... - idx := strings.Index(parentPath, "/src/") - if idx == -1 { - return url - } - return strings.TrimSuffix(urlPrefix, "/") + parentPath[:idx] + "/" + url - } - - // sysuser@xxx:user/repo - i := strings.Index(url, "@") - j := strings.LastIndex(url, ":") - - // Only process when i < j because git+ssh://git@git.forwardbias.in/npploader.git - if i > -1 && j > -1 && i < j { - // fix problem with reverse proxy works only with local server - if strings.Contains(urlPrefix, url[i+1:j]) { - return urlPrefix + url[j+1:] - } - return "http://" + url[i+1:j] + "/" + url[j+1:] - } - - return url -} - -// RefID returns reference ID. -func (sf *SubModuleFile) RefID() string { - return sf.refID -} diff --git a/vendor/code.gitea.io/git/tag.go b/vendor/code.gitea.io/git/tag.go deleted file mode 100644 index 500fd274914c4..0000000000000 --- a/vendor/code.gitea.io/git/tag.go +++ /dev/null @@ -1,89 +0,0 @@ -// 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 git - -import ( - "bytes" - "sort" -) - -// Tag represents a Git tag. -type Tag struct { - Name string - ID SHA1 - repo *Repository - Object SHA1 // The id of this commit object - Type string - Tagger *Signature - Message string -} - -// Commit return the commit of the tag reference -func (tag *Tag) Commit() (*Commit, error) { - return tag.repo.getCommit(tag.Object) -} - -// Parse commit information from the (uncompressed) raw -// data from the commit object. -// \n\n separate headers from message -func parseTagData(data []byte) (*Tag, error) { - tag := new(Tag) - // we now have the contents of the commit object. Let's investigate... - nextline := 0 -l: - for { - eol := bytes.IndexByte(data[nextline:], '\n') - switch { - case eol > 0: - line := data[nextline : nextline+eol] - spacepos := bytes.IndexByte(line, ' ') - reftype := line[:spacepos] - switch string(reftype) { - case "object": - id, err := NewIDFromString(string(line[spacepos+1:])) - if err != nil { - return nil, err - } - tag.Object = id - case "type": - // A commit can have one or more parents - tag.Type = string(line[spacepos+1:]) - case "tagger": - sig, err := newSignatureFromCommitline(line[spacepos+1:]) - if err != nil { - return nil, err - } - tag.Tagger = sig - } - nextline += eol + 1 - case eol == 0: - tag.Message = string(data[nextline+1:]) - break l - default: - break l - } - } - return tag, nil -} - -type tagSorter []*Tag - -func (ts tagSorter) Len() int { - return len([]*Tag(ts)) -} - -func (ts tagSorter) Less(i, j int) bool { - return []*Tag(ts)[i].Tagger.When.After([]*Tag(ts)[j].Tagger.When) -} - -func (ts tagSorter) Swap(i, j int) { - []*Tag(ts)[i], []*Tag(ts)[j] = []*Tag(ts)[j], []*Tag(ts)[i] -} - -// sortTagsByTime -func sortTagsByTime(tags []*Tag) { - sorter := tagSorter(tags) - sort.Sort(sorter) -} diff --git a/vendor/code.gitea.io/git/tree.go b/vendor/code.gitea.io/git/tree.go deleted file mode 100644 index 4654dac30ea7c..0000000000000 --- a/vendor/code.gitea.io/git/tree.go +++ /dev/null @@ -1,72 +0,0 @@ -// 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 git - -import ( - "strings" -) - -// Tree represents a flat directory listing. -type Tree struct { - ID SHA1 - repo *Repository - - // parent tree - ptree *Tree - - entries Entries - entriesParsed bool -} - -// NewTree create a new tree according the repository and commit id -func NewTree(repo *Repository, id SHA1) *Tree { - return &Tree{ - ID: id, - repo: repo, - } -} - -// SubTree get a sub tree by the sub dir path -func (t *Tree) SubTree(rpath string) (*Tree, error) { - if len(rpath) == 0 { - return t, nil - } - - paths := strings.Split(rpath, "/") - var ( - err error - g = t - p = t - te *TreeEntry - ) - for _, name := range paths { - te, err = p.GetTreeEntryByPath(name) - if err != nil { - return nil, err - } - - g, err = t.repo.getTree(te.ID) - if err != nil { - return nil, err - } - g.ptree = p - p = g - } - return g, nil -} - -// ListEntries returns all entries of current tree. -func (t *Tree) ListEntries() (Entries, error) { - if t.entriesParsed { - return t.entries, nil - } - - stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path) - if err != nil { - return nil, err - } - t.entries, err = parseTreeEntries(stdout, t) - return t.entries, err -} diff --git a/vendor/code.gitea.io/git/tree_blob.go b/vendor/code.gitea.io/git/tree_blob.go deleted file mode 100644 index b3d205d8e10e9..0000000000000 --- a/vendor/code.gitea.io/git/tree_blob.go +++ /dev/null @@ -1,59 +0,0 @@ -// 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 git - -import ( - "path" - "strings" -) - -// GetTreeEntryByPath get the tree entries accroding the sub dir -func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { - if len(relpath) == 0 { - return &TreeEntry{ - ID: t.ID, - Type: ObjectTree, - mode: EntryModeTree, - }, nil - } - - relpath = path.Clean(relpath) - parts := strings.Split(relpath, "/") - var err error - tree := t - for i, name := range parts { - if i == len(parts)-1 { - entries, err := tree.ListEntries() - if err != nil { - return nil, err - } - for _, v := range entries { - if v.name == name { - return v, nil - } - } - } else { - tree, err = tree.SubTree(name) - if err != nil { - return nil, err - } - } - } - return nil, ErrNotExist{"", relpath} -} - -// GetBlobByPath get the blob object accroding the path -func (t *Tree) GetBlobByPath(relpath string) (*Blob, error) { - entry, err := t.GetTreeEntryByPath(relpath) - if err != nil { - return nil, err - } - - if !entry.IsDir() { - return entry.Blob(), nil - } - - return nil, ErrNotExist{"", relpath} -} diff --git a/vendor/code.gitea.io/git/tree_entry.go b/vendor/code.gitea.io/git/tree_entry.go deleted file mode 100644 index 6201eef8fd5bd..0000000000000 --- a/vendor/code.gitea.io/git/tree_entry.go +++ /dev/null @@ -1,200 +0,0 @@ -// 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 git - -import ( - "io" - "sort" - "strconv" - "strings" -) - -// EntryMode the type of the object in the git tree -type EntryMode int - -// There are only a few file modes in Git. They look like unix file modes, but they can only be -// one of these. -const ( - // EntryModeBlob - EntryModeBlob EntryMode = 0100644 - // EntryModeExec - EntryModeExec EntryMode = 0100755 - // EntryModeSymlink - EntryModeSymlink EntryMode = 0120000 - // EntryModeCommit - EntryModeCommit EntryMode = 0160000 - // EntryModeTree - EntryModeTree EntryMode = 0040000 -) - -// TreeEntry the leaf in the git tree -type TreeEntry struct { - ID SHA1 - Type ObjectType - - mode EntryMode - name string - - ptree *Tree - - commited bool - - size int64 - sized bool -} - -// Name returns the name of the entry -func (te *TreeEntry) Name() string { - return te.name -} - -// Size returns the size of the entry -func (te *TreeEntry) Size() int64 { - if te.IsDir() { - return 0 - } else if te.sized { - return te.size - } - - stdout, err := NewCommand("cat-file", "-s", te.ID.String()).RunInDir(te.ptree.repo.Path) - if err != nil { - return 0 - } - - te.sized = true - te.size, _ = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) - return te.size -} - -// IsSubModule if the entry is a sub module -func (te *TreeEntry) IsSubModule() bool { - return te.mode == EntryModeCommit -} - -// IsDir if the entry is a sub dir -func (te *TreeEntry) IsDir() bool { - return te.mode == EntryModeTree -} - -// IsLink if the entry is a symlink -func (te *TreeEntry) IsLink() bool { - return te.mode == EntryModeSymlink -} - -// Blob retrun the blob object the entry -func (te *TreeEntry) Blob() *Blob { - return &Blob{ - repo: te.ptree.repo, - TreeEntry: te, - } -} - -// FollowLink returns the entry pointed to by a symlink -func (te *TreeEntry) FollowLink() (*TreeEntry, error) { - if !te.IsLink() { - return nil, ErrBadLink{te.Name(), "not a symlink"} - } - - // read the link - r, err := te.Blob().Data() - if err != nil { - return nil, err - } - buf := make([]byte, te.Size()) - _, err = io.ReadFull(r, buf) - if err != nil { - return nil, err - } - - lnk := string(buf) - t := te.ptree - - // traverse up directories - for ; t != nil && strings.HasPrefix(lnk, "../"); lnk = lnk[3:] { - t = t.ptree - } - - if t == nil { - return nil, ErrBadLink{te.Name(), "points outside of repo"} - } - - target, err := t.GetTreeEntryByPath(lnk) - if err != nil { - if IsErrNotExist(err) { - return nil, ErrBadLink{te.Name(), "broken link"} - } - return nil, err - } - return target, nil -} - -// GetSubJumpablePathName return the full path of subdirectory jumpable ( contains only one directory ) -func (te *TreeEntry) GetSubJumpablePathName() string { - if te.IsSubModule() || !te.IsDir() { - return "" - } - tree, err := te.ptree.SubTree(te.name) - if err != nil { - return te.name - } - entries, _ := tree.ListEntries() - if len(entries) == 1 && entries[0].IsDir() { - name := entries[0].GetSubJumpablePathName() - if name != "" { - return te.name + "/" + name - } - } - return te.name -} - -// Entries a list of entry -type Entries []*TreeEntry - -type customSortableEntries struct { - Comparer func(s1, s2 string) bool - Entries -} - -var sorter = []func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool{ - func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { - return (t1.IsDir() || t1.IsSubModule()) && !t2.IsDir() && !t2.IsSubModule() - }, - func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { - return cmp(t1.name, t2.name) - }, -} - -func (ctes customSortableEntries) Len() int { return len(ctes.Entries) } - -func (ctes customSortableEntries) Swap(i, j int) { - ctes.Entries[i], ctes.Entries[j] = ctes.Entries[j], ctes.Entries[i] -} - -func (ctes customSortableEntries) Less(i, j int) bool { - t1, t2 := ctes.Entries[i], ctes.Entries[j] - var k int - for k = 0; k < len(sorter)-1; k++ { - s := sorter[k] - switch { - case s(t1, t2, ctes.Comparer): - return true - case s(t2, t1, ctes.Comparer): - return false - } - } - return sorter[k](t1, t2, ctes.Comparer) -} - -// Sort sort the list of entry -func (tes Entries) Sort() { - sort.Sort(customSortableEntries{func(s1, s2 string) bool { - return s1 < s2 - }, tes}) -} - -// CustomSort customizable string comparing sort entry list -func (tes Entries) CustomSort(cmp func(s1, s2 string) bool) { - sort.Sort(customSortableEntries{cmp, tes}) -} diff --git a/vendor/code.gitea.io/git/utils.go b/vendor/code.gitea.io/git/utils.go deleted file mode 100644 index 8f010321cf836..0000000000000 --- a/vendor/code.gitea.io/git/utils.go +++ /dev/null @@ -1,96 +0,0 @@ -// 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 git - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "sync" -) - -// ObjectCache provides thread-safe cache opeations. -type ObjectCache struct { - lock sync.RWMutex - cache map[string]interface{} -} - -func newObjectCache() *ObjectCache { - return &ObjectCache{ - cache: make(map[string]interface{}, 10), - } -} - -// Set add obj to cache -func (oc *ObjectCache) Set(id string, obj interface{}) { - oc.lock.Lock() - defer oc.lock.Unlock() - - oc.cache[id] = obj -} - -// Get get cached obj by id -func (oc *ObjectCache) Get(id string) (interface{}, bool) { - oc.lock.RLock() - defer oc.lock.RUnlock() - - obj, has := oc.cache[id] - return obj, has -} - -// isDir returns true if given path is a directory, -// or returns false when it's a file or does not exist. -func isDir(dir string) bool { - f, e := os.Stat(dir) - if e != nil { - return false - } - return f.IsDir() -} - -// isFile returns true if given path is a file, -// or returns false when it's a directory or does not exist. -func isFile(filePath string) bool { - f, e := os.Stat(filePath) - if e != nil { - return false - } - return !f.IsDir() -} - -// isExist checks whether a file or directory exists. -// It returns false when the file or directory does not exist. -func isExist(path string) bool { - _, err := os.Stat(path) - return err == nil || os.IsExist(err) -} - -func concatenateError(err error, stderr string) error { - if len(stderr) == 0 { - return err - } - return fmt.Errorf("%v - %s", err, stderr) -} - -// If the object is stored in its own file (i.e not in a pack file), -// this function returns the full path to the object file. -// It does not test if the file exists. -func filepathFromSHA1(rootdir, sha1 string) string { - return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:]) -} - -// RefEndName return the end name of a ref name -func RefEndName(refStr string) string { - if strings.HasPrefix(refStr, BranchPrefix) { - return refStr[len(BranchPrefix):] - } - - if strings.HasPrefix(refStr, TagPrefix) { - return refStr[len(TagPrefix):] - } - - return refStr -} diff --git a/vendor/code.gitea.io/sdk/LICENSE b/vendor/code.gitea.io/sdk/LICENSE deleted file mode 100644 index 10aeba46bcfc9..0000000000000 --- a/vendor/code.gitea.io/sdk/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 4071b6f187fcc..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/admin_org.go +++ /dev/null @@ -1,22 +0,0 @@ -// 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" -) - -// 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 deleted file mode 100644 index cf565ffa38b1c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/admin_repo.go +++ /dev/null @@ -1,22 +0,0 @@ -// 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/attachment.go b/vendor/code.gitea.io/sdk/gitea/attachment.go deleted file mode 100644 index 8c527de735c39..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/attachment.go +++ /dev/null @@ -1,92 +0,0 @@ -// 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 -// swagger:model -type Attachment struct { - ID int64 `json:"id"` - Name string `json:"name"` - Size int64 `json:"size"` - DownloadCount int64 `json:"download_count"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - UUID string `json:"uuid"` - DownloadURL string `json:"browser_download_url"` -} - -// ListReleaseAttachments list release's attachments -func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*Attachment, error) { - attachments := make([]*Attachment, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), - 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 -} - -// 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 -} - -// EditAttachmentOptions options for editing attachments -// swagger:model -type EditAttachmentOptions struct { - Name string `json:"name"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/doc.go b/vendor/code.gitea.io/sdk/gitea/doc.go deleted file mode 100644 index 6bd327db4623c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// 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 deleted file mode 100644 index 57222498ef54c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/fork.go +++ /dev/null @@ -1,39 +0,0 @@ -// 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" -) - -// ListForks list a repository's forks -func (c *Client) ListForks(user, repo string) ([]*Repository, error) { - forks := make([]*Repository, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/forks", user, repo), - nil, nil, &forks) - return forks, err -} - -// 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) - err = c.getParsedResponse("POST", - fmt.Sprintf("/repos/%s/%s/forks", user, repo), - jsonHeader, bytes.NewReader(body), &fork) - return fork, err -} diff --git a/vendor/code.gitea.io/sdk/gitea/gitea.go b/vendor/code.gitea.io/sdk/gitea/gitea.go deleted file mode 100644 index 374a3faa9604c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/gitea.go +++ /dev/null @@ -1,104 +0,0 @@ -// 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 ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Version return the library version -func Version() string { - return "0.12.3" -} - -// Client represents a Gogs API client. -type Client struct { - url string - accessToken string - client *http.Client -} - -// NewClient initializes and returns a API client. -func NewClient(url, token string) *Client { - return &Client{ - url: strings.TrimSuffix(url, "/"), - accessToken: token, - client: &http.Client{}, - } -} - -// SetHTTPClient replaces default http.Client with user given one. -func (c *Client) SetHTTPClient(client *http.Client) { - c.client = client -} - -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 - } - req.Header.Set("Authorization", "token "+c.accessToken) - 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 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 { - return nil, err - } - 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/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go deleted file mode 100644 index f346381679848..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/hook.go +++ /dev/null @@ -1,531 +0,0 @@ -// 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" - "errors" - "fmt" - "strings" - "time" -) - -var ( - // ErrInvalidReceiveHook FIXME - ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") -) - -// 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"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` -} - -// HookList represents a list of API hook. -type HookList []*Hook - -// ListOrgHooks list all the hooks of one organization -func (c *Client) ListOrgHooks(org string) (HookList, error) { - hooks := make([]*Hook, 0, 10) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks", org), nil, nil, &hooks) -} - -// ListRepoHooks list all the hooks of one repository -func (c *Client) ListRepoHooks(user, repo string) (HookList, error) { - hooks := make([]*Hook, 0, 10) - return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), 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 { - // required: true - // enum: gitea,gogs,slack,discord - Type string `json:"type" binding:"Required"` - // required: true - Config map[string]string `json:"config" binding:"Required"` - Events []string `json:"events"` - // default: false - 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"` - 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("/org/%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 -} - -// Payloader payload is some part of one hook -type Payloader interface { - SetSecret(string) - JSONPayload() ([]byte, error) -} - -// PayloadUser represents the author or committer of a commit -type PayloadUser struct { - // Full name of the commit author - Name string `json:"name"` - // swagger:strfmt email - 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"` - // swagger:strfmt date-time - Timestamp time.Time `json:"timestamp"` -} - -// 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"` -} - -var ( - _ Payloader = &CreatePayload{} - _ Payloader = &DeletePayload{} - _ Payloader = &ForkPayload{} - _ Payloader = &PushPayload{} - _ Payloader = &IssuePayload{} - _ Payloader = &IssueCommentPayload{} - _ Payloader = &PullRequestPayload{} - _ Payloader = &RepositoryPayload{} - _ Payloader = &ReleasePayload{} -) - -// _________ __ -// \_ ___ \_______ ____ _____ _/ |_ ____ -// / \ \/\_ __ \_/ __ \\__ \\ __\/ __ \ -// \ \____| | \/\ ___/ / __ \| | \ ___/ -// \______ /|__| \___ >____ /__| \___ > -// \/ \/ \/ \/ - -// CreatePayload FIXME -type CreatePayload struct { - Secret string `json:"secret"` - Sha string `json:"sha"` - Ref string `json:"ref"` - RefType string `json:"ref_type"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret FIXME -func (p *CreatePayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload return payload information -func (p *CreatePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ParseCreateHook parses create event hook content. -func ParseCreateHook(raw []byte) (*CreatePayload, error) { - hook := new(CreatePayload) - if err := json.Unmarshal(raw, hook); err != nil { - return nil, err - } - - // it is possible the JSON was parsed, however, - // was not from Gogs (maybe was from Bitbucket) - // So we'll check to be sure certain key fields - // were populated - switch { - case hook.Repo == nil: - return nil, ErrInvalidReceiveHook - case len(hook.Ref) == 0: - return nil, ErrInvalidReceiveHook - } - return hook, nil -} - -// ________ .__ __ -// \______ \ ____ | | _____/ |_ ____ -// | | \_/ __ \| | _/ __ \ __\/ __ \ -// | ` \ ___/| |_\ ___/| | \ ___/ -// /_______ /\___ >____/\___ >__| \___ > -// \/ \/ \/ \/ - -// PusherType define the type to push -type PusherType string - -// describe all the PusherTypes -const ( - PusherTypeUser PusherType = "user" -) - -// DeletePayload represents delete payload -type DeletePayload struct { - Ref string `json:"ref"` - RefType string `json:"ref_type"` - PusherType PusherType `json:"pusher_type"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *DeletePayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *DeletePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ___________ __ -// \_ _____/__________| | __ -// | __)/ _ \_ __ \ |/ / -// | \( <_> ) | \/ < -// \___ / \____/|__| |__|_ \ -// \/ \/ - -// ForkPayload represents fork payload -type ForkPayload struct { - Forkee *Repository `json:"forkee"` - Repo *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *ForkPayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *ForkPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// HookIssueCommentAction defines hook issue comment action -type HookIssueCommentAction string - -// all issue comment actions -const ( - HookIssueCommentCreated HookIssueCommentAction = "created" - HookIssueCommentEdited HookIssueCommentAction = "edited" - HookIssueCommentDeleted HookIssueCommentAction = "deleted" -) - -// IssueCommentPayload represents a payload information of issue comment event. -type IssueCommentPayload struct { - Action HookIssueCommentAction `json:"action"` - Issue *Issue `json:"issue"` - Comment *Comment `json:"comment"` - Changes *ChangesPayload `json:"changes,omitempty"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *IssueCommentPayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *IssueCommentPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// __________ .__ -// \______ \ ____ | | ____ _____ ______ ____ -// | _// __ \| | _/ __ \\__ \ / ___// __ \ -// | | \ ___/| |_\ ___/ / __ \_\___ \\ ___/ -// |____|_ /\___ >____/\___ >____ /____ >\___ > -// \/ \/ \/ \/ \/ \/ - -// HookReleaseAction defines hook release action type -type HookReleaseAction string - -// all release actions -const ( - HookReleasePublished HookReleaseAction = "published" - HookReleaseUpdated HookReleaseAction = "updated" - HookReleaseDeleted HookReleaseAction = "deleted" -) - -// ReleasePayload represents a payload information of release event. -type ReleasePayload struct { - Action HookReleaseAction `json:"action"` - Release *Release `json:"release"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret implements Payload -func (p *ReleasePayload) SetSecret(secret string) { -} - -// JSONPayload implements Payload -func (p *ReleasePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// __________ .__ -// \______ \__ __ _____| |__ -// | ___/ | \/ ___/ | \ -// | | | | /\___ \| Y \ -// |____| |____//____ >___| / -// \/ \/ - -// PushPayload represents a payload information of push event. -type PushPayload struct { - Secret string `json:"secret"` - Ref string `json:"ref"` - Before string `json:"before"` - After string `json:"after"` - CompareURL string `json:"compare_url"` - Commits []*PayloadCommit `json:"commits"` - Repo *Repository `json:"repository"` - Pusher *User `json:"pusher"` - Sender *User `json:"sender"` -} - -// SetSecret FIXME -func (p *PushPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload FIXME -func (p *PushPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ParsePushHook parses push event hook content. -func ParsePushHook(raw []byte) (*PushPayload, error) { - hook := new(PushPayload) - if err := json.Unmarshal(raw, hook); err != nil { - return nil, err - } - - switch { - case hook.Repo == nil: - return nil, ErrInvalidReceiveHook - case len(hook.Ref) == 0: - return nil, ErrInvalidReceiveHook - } - return hook, nil -} - -// Branch returns branch name from a payload -func (p *PushPayload) Branch() string { - return strings.Replace(p.Ref, "refs/heads/", "", -1) -} - -// .___ -// | | ______ ________ __ ____ -// | |/ ___// ___/ | \_/ __ \ -// | |\___ \ \___ \| | /\ ___/ -// |___/____ >____ >____/ \___ > -// \/ \/ \/ - -// HookIssueAction FIXME -type HookIssueAction string - -const ( - // HookIssueOpened opened - HookIssueOpened HookIssueAction = "opened" - // HookIssueClosed closed - HookIssueClosed HookIssueAction = "closed" - // HookIssueReOpened reopened - HookIssueReOpened HookIssueAction = "reopened" - // HookIssueEdited edited - HookIssueEdited HookIssueAction = "edited" - // HookIssueAssigned assigned - HookIssueAssigned HookIssueAction = "assigned" - // HookIssueUnassigned unassigned - HookIssueUnassigned HookIssueAction = "unassigned" - // HookIssueLabelUpdated label_updated - HookIssueLabelUpdated HookIssueAction = "label_updated" - // HookIssueLabelCleared label_cleared - HookIssueLabelCleared HookIssueAction = "label_cleared" - // HookIssueSynchronized synchronized - HookIssueSynchronized HookIssueAction = "synchronized" - // HookIssueMilestoned is an issue action for when a milestone is set on an issue. - HookIssueMilestoned HookIssueAction = "milestoned" - // HookIssueDemilestoned is an issue action for when a milestone is cleared on an issue. - HookIssueDemilestoned HookIssueAction = "demilestoned" -) - -// IssuePayload represents the payload information that is sent along with an issue event. -type IssuePayload struct { - Secret string `json:"secret"` - Action HookIssueAction `json:"action"` - Index int64 `json:"number"` - Changes *ChangesPayload `json:"changes,omitempty"` - Issue *Issue `json:"issue"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret modifies the secret of the IssuePayload. -func (p *IssuePayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload encodes the IssuePayload to JSON, with an indentation of two spaces. -func (p *IssuePayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -// ChangesFromPayload FIXME -type ChangesFromPayload struct { - From string `json:"from"` -} - -// ChangesPayload FIXME -type ChangesPayload struct { - Title *ChangesFromPayload `json:"title,omitempty"` - Body *ChangesFromPayload `json:"body,omitempty"` -} - -// __________ .__ .__ __________ __ -// \______ \__ __| | | | \______ \ ____ ________ __ ____ _______/ |_ -// | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\ -// | | | | / |_| |__ | | \ ___< <_| | | /\ ___/ \___ \ | | -// |____| |____/|____/____/ |____|_ /\___ >__ |____/ \___ >____ > |__| -// \/ \/ |__| \/ \/ - -// PullRequestPayload represents a payload information of pull request event. -type PullRequestPayload struct { - Secret string `json:"secret"` - Action HookIssueAction `json:"action"` - Index int64 `json:"number"` - Changes *ChangesPayload `json:"changes,omitempty"` - PullRequest *PullRequest `json:"pull_request"` - Repository *Repository `json:"repository"` - Sender *User `json:"sender"` -} - -// SetSecret modifies the secret of the PullRequestPayload. -func (p *PullRequestPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload FIXME -func (p *PullRequestPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} - -//__________ .__ __ -//\______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. -// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | -// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ | -// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| -// \/ \/|__| \/ \/ - -// HookRepoAction an action that happens to a repo -type HookRepoAction string - -const ( - // HookRepoCreated created - HookRepoCreated HookRepoAction = "created" - // HookRepoDeleted deleted - HookRepoDeleted HookRepoAction = "deleted" -) - -// RepositoryPayload payload for repository webhooks -type RepositoryPayload struct { - Secret string `json:"secret"` - Action HookRepoAction `json:"action"` - Repository *Repository `json:"repository"` - Organization *User `json:"organization"` - Sender *User `json:"sender"` -} - -// SetSecret set the payload's secret -func (p *RepositoryPayload) SetSecret(secret string) { - p.Secret = secret -} - -// JSONPayload JSON representation of the payload -func (p *RepositoryPayload) JSONPayload() ([]byte, error) { - return json.MarshalIndent(p, "", " ") -} diff --git a/vendor/code.gitea.io/sdk/gitea/issue_comment.go b/vendor/code.gitea.io/sdk/gitea/issue_comment.go deleted file mode 100644 index 2c8127c609734..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_comment.go +++ /dev/null @@ -1,76 +0,0 @@ -// 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" - "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"` - Body string `json:"body"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` -} - -// ListIssueComments list comments on an issue. -func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, error) { - comments := make([]*Comment, 0, 10) - return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments) -} - -// ListRepoIssueComments list comments for a given repo. -func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) { - comments := make([]*Comment, 0, 10) - return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments) -} - -// CreateIssueCommentOption options for creating a comment on an issue -type CreateIssueCommentOption struct { - // required:true - Body string `json:"body" binding:"Required"` -} - -// 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 { - // required: true - Body string `json:"body" binding:"Required"` -} - -// EditIssueComment edits an issue comment. -func (c *Client) EditIssueComment(owner, repo string, index, 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/%d/comments/%d", owner, repo, index, commentID), jsonHeader, bytes.NewReader(body), comment) -} - -// DeleteIssueComment deletes an issue comment. -func (c *Client) DeleteIssueComment(owner, repo string, index, commentID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, 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 deleted file mode 100644 index 47d1b8221e98b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_label.go +++ /dev/null @@ -1,122 +0,0 @@ -// 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 -// swagger:model -type Label struct { - ID int64 `json:"id"` - Name string `json:"name"` - // example: 00aabb - Color string `json:"color"` - URL string `json:"url"` -} - -// ListRepoLabels list labels of one repository -func (c *Client) ListRepoLabels(owner, repo string) ([]*Label, error) { - labels := make([]*Label, 0, 10) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), nil, nil, &labels) -} - -// 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 { - // required:true - Name string `json:"name" binding:"Required"` - // required:true - // example: #00aabb - Color string `json:"color" binding:"Required;Size(7)"` -} - -// CreateLabel create one label of repository -func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { - 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"` -} - -// 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 -} - -// IssueLabelsOption a collection of labels -type IssueLabelsOption struct { - // list of label IDs - Labels []int64 `json:"labels"` -} - -// GetIssueLabels get labels of one issue via issue id -func (c *Client) GetIssueLabels(owner, repo string, index int64) ([]*Label, error) { - labels := make([]*Label, 0, 5) - return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil, &labels) -} - -// 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 deleted file mode 100644 index 775a6a9117510..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_milestone.go +++ /dev/null @@ -1,80 +0,0 @@ -// 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" - "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"` - // swagger:strfmt date-time - Closed *time.Time `json:"closed_at"` - // swagger:strfmt date-time - Deadline *time.Time `json:"due_on"` -} - -// ListRepoMilestones list all the milestones of one repository -func (c *Client) ListRepoMilestones(owner, repo string) ([]*Milestone, error) { - milestones := make([]*Milestone, 0, 10) - return milestones, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), nil, nil, &milestones) -} - -// 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"` - // swagger:strfmt date-time - 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) - return milestone, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) -} - -// 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_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go deleted file mode 100644 index 7f4b64cbb3f99..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go +++ /dev/null @@ -1,68 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created"` - // Time in seconds - Time int64 `json:"time"` - UserID int64 `json:"user_id"` - IssueID int64 `json:"issue_id"` -} - -// TrackedTimes represent a list of tracked times -type TrackedTimes []*TrackedTime - -// GetUserTrackedTimes list tracked times of a user -func (c *Client) GetUserTrackedTimes(owner, repo, user string) (TrackedTimes, error) { - times := make(TrackedTimes, 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) (TrackedTimes, error) { - times := make(TrackedTimes, 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() (TrackedTimes, error) { - times := make(TrackedTimes, 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 - // required: true - Time int64 `json:"time" binding:"Required"` -} - -// 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) -} - -// ListTrackedTimes get tracked times of one issue via issue id -func (c *Client) ListTrackedTimes(owner, repo string, index int64) (TrackedTimes, error) { - times := make(TrackedTimes, 0, 5) - return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil, ×) -} diff --git a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go deleted file mode 100644 index 356636a3a2519..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go +++ /dev/null @@ -1,65 +0,0 @@ -// 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 ( - "time" -) - -// LFSLock represent a lock -// for use with the locks API. -type LFSLock struct { - ID string `json:"id"` - Path string `json:"path"` - LockedAt time.Time `json:"locked_at"` - Owner *LFSLockOwner `json:"owner"` -} - -// LFSLockOwner represent a lock owner -// for use with the locks API. -type LFSLockOwner struct { - Name string `json:"name"` -} - -// LFSLockRequest contains the path of the lock to create -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock -type LFSLockRequest struct { - Path string `json:"path"` -} - -// LFSLockResponse represent a lock created -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock -type LFSLockResponse struct { - Lock *LFSLock `json:"lock"` -} - -// LFSLockList represent a list of lock requested -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks -type LFSLockList struct { - Locks []*LFSLock `json:"locks"` - Next string `json:"next_cursor,omitempty"` -} - -// LFSLockListVerify represent a list of lock verification requested -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks-for-verification -type LFSLockListVerify struct { - Ours []*LFSLock `json:"ours"` - Theirs []*LFSLock `json:"theirs"` - Next string `json:"next_cursor,omitempty"` -} - -// LFSLockError contains information on the error that occurs -type LFSLockError struct { - Message string `json:"message"` - Lock *LFSLock `json:"lock,omitempty"` - Documentation string `json:"documentation_url,omitempty"` - RequestID string `json:"request_id,omitempty"` -} - -// LFSLockDeleteRequest contains params of a delete request -// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#delete-lock -type LFSLockDeleteRequest struct { - Force bool `json:"force"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go deleted file mode 100644 index 3735047b7f886..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go +++ /dev/null @@ -1,52 +0,0 @@ -// 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 - -// SearchResults results of a successful search -type SearchResults struct { - OK bool `json:"ok"` - Data []*Repository `json:"data"` -} - -// SearchError error of a failed search -type SearchError struct { - OK bool `json:"ok"` - Error string `json:"error"` -} - -// MarkdownOption markdown options -type MarkdownOption struct { - // Text markdown to render - // - // in: body - Text string - // Mode to render - // - // in: body - Mode string - // Context to render - // - // in: body - Context string - // Is it a wiki page ? - // - // in: body - Wiki bool -} - -// MarkdownRender is a rendered markdown document -// swagger:response MarkdownRender -type MarkdownRender string - -// ServerVersion wraps the version of the server -type ServerVersion struct { - Version string `json:"version"` -} - -// ServerVersion returns the version of the server -func (c *Client) ServerVersion() (string, error) { - v := ServerVersion{} - return v.Version, c.getParsedResponse("GET", "/api/v1/version", nil, nil, &v) -} diff --git a/vendor/code.gitea.io/sdk/gitea/org.go b/vendor/code.gitea.io/sdk/gitea/org.go deleted file mode 100644 index 19238d1028453..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org.go +++ /dev/null @@ -1,68 +0,0 @@ -// 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" -) - -// 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"` -} - -// ListMyOrgs list all of current user's organizations -func (c *Client) ListMyOrgs() ([]*Organization, error) { - orgs := make([]*Organization, 0, 5) - return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs) -} - -// ListUserOrgs list all of some user's organizations -func (c *Client) ListUserOrgs(user string) ([]*Organization, error) { - orgs := make([]*Organization, 0, 5) - return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs) -} - -// 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 { - // required: true - UserName string `json:"username" binding:"Required"` - FullName string `json:"full_name"` - Description string `json:"description"` - Website string `json:"website"` - Location string `json:"location"` -} - -// 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"` -} - -// 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 -} diff --git a/vendor/code.gitea.io/sdk/gitea/org_member.go b/vendor/code.gitea.io/sdk/gitea/org_member.go deleted file mode 100644 index 9bb95af3e2624..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org_member.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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" -) - -// AddOrgMembershipOption add user to organization options -type AddOrgMembershipOption struct { - Role string `json:"role" binding:"Required"` -} - -// AddOrgMembership add some one to an organization's member -func (c *Client) AddOrgMembership(org, user string, opt AddOrgMembershipOption) error { - body, err := json.Marshal(&opt) - if err != nil { - return err - } - _, err = c.getResponse("PUT", fmt.Sprintf("/orgs/%s/membership/%s", org, user), jsonHeader, bytes.NewReader(body)) - return err -} diff --git a/vendor/code.gitea.io/sdk/gitea/org_team.go b/vendor/code.gitea.io/sdk/gitea/org_team.go deleted file mode 100644 index 2fc6796d43ff9..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/org_team.go +++ /dev/null @@ -1,32 +0,0 @@ -// 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 - -// Team represents a team in an organization -type Team struct { - ID int64 `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - // enum: none,read,write,admin,owner - Permission string `json:"permission"` -} - -// CreateTeamOption options for creating a team -type CreateTeamOption struct { - // required: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` - Description string `json:"description" binding:"MaxSize(255)"` - // enum: read,write,admin - Permission string `json:"permission"` -} - -// EditTeamOption options for editing a team -type EditTeamOption struct { - // required: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` - Description string `json:"description" binding:"MaxSize(255)"` - // enum: read,write,admin - Permission string `json:"permission"` -} diff --git a/vendor/code.gitea.io/sdk/gitea/pull.go b/vendor/code.gitea.io/sdk/gitea/pull.go deleted file mode 100644 index 6fcdd1d41b7e4..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/pull.go +++ /dev/null @@ -1,151 +0,0 @@ -// 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" - "time" -) - -// 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"` - // swagger:strfmt date-time - 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"` - - // swagger:strfmt date-time - Deadline *time.Time `json:"due_date"` - - // swagger:strfmt date-time - Created *time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated *time.Time `json:"updated_at"` - // swagger:strfmt date-time - Closed *time.Time `json:"closed_at"` -} - -// 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"` -} - -// ListPullRequestsOptions options for listing pull requests -type ListPullRequestsOptions struct { - Page int `json:"page"` - State string `json:"state"` -} - -// ListRepoPullRequests list PRs of one repository -func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { - body, err := json.Marshal(&opt) - if err != nil { - return nil, err - } - prs := make([]*PullRequest, 0, 10) - return prs, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), jsonHeader, bytes.NewReader(body), &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" binding:"Required"` - Base string `json:"base" binding:"Required"` - Title string `json:"title" binding:"Required"` - Body string `json:"body"` - Assignee string `json:"assignee"` - Assignees []string `json:"assignees"` - Milestone int64 `json:"milestone"` - Labels []int64 `json:"labels"` - // swagger:strfmt date-time - 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"` - Assignee string `json:"assignee"` - Assignees []string `json:"assignees"` - Milestone int64 `json:"milestone"` - Labels []int64 `json:"labels"` - State *string `json:"state"` - // swagger:strfmt date-time - 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/issues/%d", owner, repo, index), - jsonHeader, bytes.NewReader(body), pr) -} - -// MergePullRequest merge a PR to repository by PR id -func (c *Client) MergePullRequest(owner, repo string, index int64) error { - _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) - return err -} - -// 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/release.go b/vendor/code.gitea.io/sdk/gitea/release.go deleted file mode 100644 index 396251dcac9d8..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/release.go +++ /dev/null @@ -1,105 +0,0 @@ -// 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"` - // swagger:strfmt date-time - CreatedAt time.Time `json:"created_at"` - // swagger:strfmt date-time - PublishedAt time.Time `json:"published_at"` - Publisher *User `json:"author"` - Attachments []*Attachment `json:"assets"` -} - -// ListReleases list releases of a repository -func (c *Client) ListReleases(user, repo string) ([]*Release, error) { - releases := make([]*Release, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/releases", user, repo), - 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 { - // required: true - TagName string `json:"tag_name" binding:"Required"` - 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 deleted file mode 100644 index 339cbd33deaac..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo.go +++ /dev/null @@ -1,155 +0,0 @@ -// 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" - "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"` - 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` - Permissions *Permission `json:"permissions,omitempty"` -} - -// ListMyRepos lists all repositories for the authenticated user that has access to. -func (c *Client) ListMyRepos() ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos) -} - -// ListUserRepos list all repositories of one user by user's name -func (c *Client) ListUserRepos(user string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos", user), nil, nil, &repos) -} - -// ListOrgRepos list all repositories of one organization by organization's name -func (c *Client) ListOrgRepos(org string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos", org), nil, nil, &repos) -} - -// CreateRepoOption options when creating repository -// swagger:model -type CreateRepoOption struct { - // Name of the repository to create - // - // required: true - // unique: true - Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(100)"` - // Description of the repository to create - Description string `json:"description" binding:"MaxSize(255)"` - // Whether the repository is private - Private bool `json:"private"` - // 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"` -} - -// 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) -} - -// 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 { - // required: true - CloneAddr string `json:"clone_addr" binding:"Required"` - AuthUsername string `json:"auth_username"` - AuthPassword string `json:"auth_password"` - // required: true - UID int `json:"uid" binding:"Required"` - // required: true - RepoName string `json:"repo_name" binding:"Required"` - 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 deleted file mode 100644 index 481fc3386ee76..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_branch.go +++ /dev/null @@ -1,27 +0,0 @@ -// 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 ( - "fmt" -) - -// Branch represents a repository branch -type Branch struct { - Name string `json:"name"` - Commit *PayloadCommit `json:"commit"` -} - -// ListRepoBranches list all the branches of one repository -func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) { - branches := make([]*Branch, 0, 10) - return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches) -} - -// GetRepoBranch get one branch's information of one repository -func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { - b := new(Branch) - return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b) -} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go deleted file mode 100644 index bd61a22cec4f5..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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" -) - -// ListCollaborators list a repository's collaborators -func (c *Client) ListCollaborators(user, repo string) ([]*User, error) { - collaborators := make([]*User, 0, 10) - err := c.getParsedResponse("GET", - fmt.Sprintf("/repos/%s/%s/collaborators", user, repo), - nil, nil, &collaborators) - return collaborators, err -} - -// IsCollaborator check if a user is a collaborator of a repository -func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { - status, err := c.getStatusCode("GET", - fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), - nil, nil) - 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), nil, 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_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go deleted file mode 100644 index e6c89f0c0f28b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_file.go +++ /dev/null @@ -1,15 +0,0 @@ -// 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" -) - -// 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) -} diff --git a/vendor/code.gitea.io/sdk/gitea/repo_key.go b/vendor/code.gitea.io/sdk/gitea/repo_key.go deleted file mode 100644 index ec53311bdaa55..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_key.go +++ /dev/null @@ -1,69 +0,0 @@ -// 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" -) - -// DeployKey a deploy key -type DeployKey struct { - ID int64 `json:"id"` - Key string `json:"key"` - URL string `json:"url"` - Title string `json:"title"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - ReadOnly bool `json:"read_only"` -} - -// ListDeployKeys list all the deploy keys of one repository -func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) { - keys := make([]*DeployKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys) -} - -// 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) -} - -// CreateKeyOption options when creating a key -type CreateKeyOption struct { - // Title of the key to add - // - // required: true - // unique: true - Title string `json:"title" binding:"Required"` - // An armored SSH key to add - // - // required: true - // unique: true - Key string `json:"key" binding:"Required"` - // Describe if the key has only read access or read/write - // - // required: false - ReadOnly bool `json:"read_only"` -} - -// 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_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go deleted file mode 100644 index 1005f9fbd84ea..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/repo_watch.go +++ /dev/null @@ -1,41 +0,0 @@ -// 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, pass string) ([]*Repository, error) { - repos := make([]*Repository, 0, 10) - return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &repos) -} - -// WatchRepo start to watch a repository -func (c *Client) WatchRepo(user, pass, repoUser, repoName string) (*WatchInfo, error) { - i := new(WatchInfo) - return i, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, i) -} - -// UnWatchRepo start to watch a repository -func (c *Client) UnWatchRepo(user, pass, repoUser, repoName string) (int, error) { - return c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil) -} diff --git a/vendor/code.gitea.io/sdk/gitea/status.go b/vendor/code.gitea.io/sdk/gitea/status.go deleted file mode 100644 index 3060ab1b2b23b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/status.go +++ /dev/null @@ -1,97 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at"` - // swagger:strfmt date-time - Updated time.Time `json:"updated_at"` -} - -// 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"` -} - -// 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"` -} - -// ListStatusesOption holds pagination information -type ListStatusesOption struct { - Page int -} - -// CreateStatus creates a new Status for a given Commit -// -// POST /repos/:owner/:repo/statuses/:sha -func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { - body, err := json.Marshal(&opts) - if err != nil { - return nil, err - } - status := &Status{} - return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), - jsonHeader, bytes.NewReader(body), status) -} - -// ListStatuses returns all statuses for a given Commit -// -// GET /repos/:owner/:repo/commits/:ref/statuses -func (c *Client) ListStatuses(owner, repo, sha string, opts ListStatusesOption) ([]*Status, error) { - statuses := make([]*Status, 0, 10) - return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?page=%d", owner, repo, sha, opts.Page), nil, nil, &statuses) -} - -// GetCombinedStatus returns the CombinedStatus for a given Commit -// -// GET /repos/:owner/:repo/commits/:ref/status -func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { - status := &CombinedStatus{} - 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 deleted file mode 100644 index 57cf752316660..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user.go +++ /dev/null @@ -1,51 +0,0 @@ -// 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 ( - "encoding/json" - "fmt" -) - -// User represents a user -// swagger:model -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"` - // swagger:strfmt email - Email string `json:"email"` - // URL to the user's avatar - AvatarURL string `json:"avatar_url"` - // User locale - Language string `json:"language"` -} - -// MarshalJSON implements the json.Marshaler interface for User, adding field(s) for backward compatibility -func (u User) MarshalJSON() ([]byte, error) { - // Re-declaring User to avoid recursion - type shadow User - return json.Marshal(struct { - shadow - CompatUserName string `json:"username"` - }{shadow(u), u.UserName}) -} - -// 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 deleted file mode 100644 index d3bfce971bad4..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_app.go +++ /dev/null @@ -1,63 +0,0 @@ -// 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/base64" - "encoding/json" - "fmt" - "net/http" -) - -// BasicAuthEncode generate base64 of basic auth head -func BasicAuthEncode(user, pass string) string { - return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass)) -} - -// AccessToken represents a API access token. -// swagger:response AccessToken -type AccessToken struct { - ID int64 `json:"id"` - Name string `json:"name"` - Sha1 string `json:"sha1"` -} - -// AccessTokenList represents a list of API access token. -// swagger:response AccessTokenList -type AccessTokenList []*AccessToken - -// ListAccessTokens lista all the access tokens of user -func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) { - tokens := make([]*AccessToken, 0, 10) - return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user), - http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens) -} - -// CreateAccessTokenOption options when create access token -// swagger:parameters userCreateToken -type CreateAccessTokenOption struct { - Name string `json:"name" binding:"Required"` -} - -// CreateAccessToken create one access token with options -func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) { - body, err := json.Marshal(&opt) - if err != nil { - return nil, err - } - t := new(AccessToken) - return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user), - http.Header{ - "content-type": []string{"application/json"}, - "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, - bytes.NewReader(body), t) -} - -// DeleteAccessToken delete token with key id -func (c *Client) DeleteAccessToken(user string, keyID int64) error { - _, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, 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 deleted file mode 100644 index 721f52144ba11..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_email.go +++ /dev/null @@ -1,56 +0,0 @@ -// 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" -) - -// Email an email address belonging to a user -type Email struct { - // swagger:strfmt email - Email string `json:"email"` - Verified bool `json:"verified"` - Primary bool `json:"primary"` -} - -// ListEmails all the email addresses of user -func (c *Client) ListEmails() ([]*Email, error) { - emails := make([]*Email, 0, 3) - return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails) -} - -// 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 deleted file mode 100644 index a197a7f188220..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_follow.go +++ /dev/null @@ -1,55 +0,0 @@ -// 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" - -// ListMyFollowers list all the followers of current user -func (c *Client) ListMyFollowers(page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users) -} - -// ListFollowers list all the followers of one user -func (c *Client) ListFollowers(user string, page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users) -} - -// ListMyFollowing list all the users current user followed -func (c *Client) ListMyFollowing(page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users) -} - -// ListFollowing list all the users the user followed -func (c *Client) ListFollowing(user string, page int) ([]*User, error) { - users := make([]*User, 0, 10) - return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users) -} - -// 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 deleted file mode 100644 index 0817d89461a1c..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go +++ /dev/null @@ -1,80 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` - // swagger:strfmt date-time - Expires time.Time `json:"expires_at,omitempty"` -} - -// GPGKeyEmail an email attached to a GPGKey -// swagger:model GPGKeyEmail -type GPGKeyEmail struct { - Email string `json:"email"` - Verified bool `json:"verified"` -} - -// CreateGPGKeyOption options create user GPG key -type CreateGPGKeyOption struct { - // An armored GPG key to add - // - // required: true - // unique: true - ArmoredKey string `json:"armored_public_key" binding:"Required"` -} - -// ListGPGKeys list all the GPG keys of the user -func (c *Client) ListGPGKeys(user string) ([]*GPGKey, error) { - keys := make([]*GPGKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys", user), nil, nil, &keys) -} - -// ListMyGPGKeys list all the GPG keys of current user -func (c *Client) ListMyGPGKeys() ([]*GPGKey, error) { - keys := make([]*GPGKey, 0, 10) - return keys, c.getParsedResponse("GET", "/user/gpg_keys", nil, nil, &keys) -} - -// 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) -} - -// 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 deleted file mode 100644 index 4488c033f1a37..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_key.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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"` - // swagger:strfmt date-time - Created time.Time `json:"created_at,omitempty"` -} - -// ListPublicKeys list all the public keys of the user -func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) { - keys := make([]*PublicKey, 0, 10) - return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys) -} - -// ListMyPublicKeys list all the public keys of current user -func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) { - keys := make([]*PublicKey, 0, 10) - return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys) -} - -// 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) -} - -// 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 deleted file mode 100644 index 65ab980d66f86..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/user_search.go +++ /dev/null @@ -1,14 +0,0 @@ -package gitea - -import "fmt" - -type searchUsersResponse struct { - Users []*User `json:"data"` -} - -// SearchUsers finds users by query -func (c *Client) SearchUsers(query string, limit int) ([]*User, error) { - resp := new(searchUsersResponse) - err := c.getParsedResponse("GET", fmt.Sprintf("/users/search?q=%s&limit=%d", query, limit), nil, nil, &resp) - return resp.Users, err -} diff --git a/vendor/code.gitea.io/sdk/gitea/utils.go b/vendor/code.gitea.io/sdk/gitea/utils.go deleted file mode 100644 index 80892a1e7a90b..0000000000000 --- a/vendor/code.gitea.io/sdk/gitea/utils.go +++ /dev/null @@ -1,26 +0,0 @@ -// 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 ( - "net/http" -) - -var jsonHeader = http.Header{"content-type": []string{"application/json"}} - -// Bool return address of bool value -func Bool(v bool) *bool { - return &v -} - -// String return address of string value -func String(v string) *string { - return &v -} - -// Int64 return address of int64 value -func Int64(v int64) *int64 { - return &v -} From 656ae37057ad85573af832ebb68db5904a9dd9d6 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Thu, 30 Aug 2018 01:42:56 +0800 Subject: [PATCH 14/21] recovery vendor. Signed-off-by: BetaCat0 outman99@hotmail.com --- vendor/code.gitea.io/git/LICENSE | 20 + vendor/code.gitea.io/git/blob.go | 73 +++ vendor/code.gitea.io/git/command.go | 134 +++++ vendor/code.gitea.io/git/commit.go | 276 +++++++++ vendor/code.gitea.io/git/commit_archive.go | 37 ++ vendor/code.gitea.io/git/commit_info.go | 319 +++++++++++ vendor/code.gitea.io/git/doc.go | 5 + vendor/code.gitea.io/git/error.go | 66 +++ vendor/code.gitea.io/git/git.go | 91 +++ vendor/code.gitea.io/git/hook.go | 126 +++++ vendor/code.gitea.io/git/parse.go | 81 +++ vendor/code.gitea.io/git/repo.go | 287 ++++++++++ vendor/code.gitea.io/git/repo_blame.go | 24 + vendor/code.gitea.io/git/repo_branch.go | 123 ++++ vendor/code.gitea.io/git/repo_commit.go | 352 ++++++++++++ vendor/code.gitea.io/git/repo_hook.go | 15 + vendor/code.gitea.io/git/repo_object.go | 19 + vendor/code.gitea.io/git/repo_pull.go | 89 +++ vendor/code.gitea.io/git/repo_tag.go | 157 ++++++ vendor/code.gitea.io/git/repo_tree.go | 26 + vendor/code.gitea.io/git/sha1.go | 76 +++ vendor/code.gitea.io/git/signature.go | 58 ++ vendor/code.gitea.io/git/submodule.go | 79 +++ vendor/code.gitea.io/git/tag.go | 89 +++ vendor/code.gitea.io/git/tree.go | 72 +++ vendor/code.gitea.io/git/tree_blob.go | 59 ++ vendor/code.gitea.io/git/tree_entry.go | 200 +++++++ vendor/code.gitea.io/git/utils.go | 96 ++++ vendor/code.gitea.io/sdk/LICENSE | 20 + vendor/code.gitea.io/sdk/gitea/admin_org.go | 22 + vendor/code.gitea.io/sdk/gitea/admin_repo.go | 22 + vendor/code.gitea.io/sdk/gitea/attachment.go | 92 +++ vendor/code.gitea.io/sdk/gitea/doc.go | 5 + vendor/code.gitea.io/sdk/gitea/fork.go | 39 ++ vendor/code.gitea.io/sdk/gitea/gitea.go | 104 ++++ vendor/code.gitea.io/sdk/gitea/hook.go | 531 ++++++++++++++++++ .../code.gitea.io/sdk/gitea/issue_comment.go | 76 +++ vendor/code.gitea.io/sdk/gitea/issue_label.go | 122 ++++ .../sdk/gitea/issue_milestone.go | 80 +++ .../sdk/gitea/issue_tracked_time.go | 68 +++ vendor/code.gitea.io/sdk/gitea/lfs_lock.go | 65 +++ .../code.gitea.io/sdk/gitea/miscellaneous.go | 52 ++ vendor/code.gitea.io/sdk/gitea/org.go | 68 +++ vendor/code.gitea.io/sdk/gitea/org_member.go | 26 + vendor/code.gitea.io/sdk/gitea/org_team.go | 32 ++ vendor/code.gitea.io/sdk/gitea/pull.go | 151 +++++ vendor/code.gitea.io/sdk/gitea/release.go | 105 ++++ vendor/code.gitea.io/sdk/gitea/repo.go | 155 +++++ vendor/code.gitea.io/sdk/gitea/repo_branch.go | 27 + .../sdk/gitea/repo_collaborator.go | 57 ++ vendor/code.gitea.io/sdk/gitea/repo_file.go | 15 + vendor/code.gitea.io/sdk/gitea/repo_key.go | 69 +++ vendor/code.gitea.io/sdk/gitea/repo_watch.go | 41 ++ vendor/code.gitea.io/sdk/gitea/status.go | 97 ++++ vendor/code.gitea.io/sdk/gitea/user.go | 51 ++ vendor/code.gitea.io/sdk/gitea/user_app.go | 63 +++ vendor/code.gitea.io/sdk/gitea/user_email.go | 56 ++ vendor/code.gitea.io/sdk/gitea/user_follow.go | 55 ++ vendor/code.gitea.io/sdk/gitea/user_gpgkey.go | 80 +++ vendor/code.gitea.io/sdk/gitea/user_key.go | 57 ++ vendor/code.gitea.io/sdk/gitea/user_search.go | 14 + vendor/code.gitea.io/sdk/gitea/utils.go | 26 + 62 files changed, 5592 insertions(+) create mode 100644 vendor/code.gitea.io/git/LICENSE create mode 100644 vendor/code.gitea.io/git/blob.go create mode 100644 vendor/code.gitea.io/git/command.go create mode 100644 vendor/code.gitea.io/git/commit.go create mode 100644 vendor/code.gitea.io/git/commit_archive.go create mode 100644 vendor/code.gitea.io/git/commit_info.go create mode 100644 vendor/code.gitea.io/git/doc.go create mode 100644 vendor/code.gitea.io/git/error.go create mode 100644 vendor/code.gitea.io/git/git.go create mode 100644 vendor/code.gitea.io/git/hook.go create mode 100644 vendor/code.gitea.io/git/parse.go create mode 100644 vendor/code.gitea.io/git/repo.go create mode 100644 vendor/code.gitea.io/git/repo_blame.go create mode 100644 vendor/code.gitea.io/git/repo_branch.go create mode 100644 vendor/code.gitea.io/git/repo_commit.go create mode 100644 vendor/code.gitea.io/git/repo_hook.go create mode 100644 vendor/code.gitea.io/git/repo_object.go create mode 100644 vendor/code.gitea.io/git/repo_pull.go create mode 100644 vendor/code.gitea.io/git/repo_tag.go create mode 100644 vendor/code.gitea.io/git/repo_tree.go create mode 100644 vendor/code.gitea.io/git/sha1.go create mode 100644 vendor/code.gitea.io/git/signature.go create mode 100644 vendor/code.gitea.io/git/submodule.go create mode 100644 vendor/code.gitea.io/git/tag.go create mode 100644 vendor/code.gitea.io/git/tree.go create mode 100644 vendor/code.gitea.io/git/tree_blob.go create mode 100644 vendor/code.gitea.io/git/tree_entry.go create mode 100644 vendor/code.gitea.io/git/utils.go create mode 100644 vendor/code.gitea.io/sdk/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/attachment.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/gitea.go create mode 100644 vendor/code.gitea.io/sdk/gitea/hook.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_tracked_time.go create mode 100644 vendor/code.gitea.io/sdk/gitea/lfs_lock.go create mode 100644 vendor/code.gitea.io/sdk/gitea/miscellaneous.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/pull.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_collaborator.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_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/utils.go diff --git a/vendor/code.gitea.io/git/LICENSE b/vendor/code.gitea.io/git/LICENSE new file mode 100644 index 0000000000000..10aeba46bcfc9 --- /dev/null +++ b/vendor/code.gitea.io/git/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/git/blob.go b/vendor/code.gitea.io/git/blob.go new file mode 100644 index 0000000000000..a6e392eeb50a6 --- /dev/null +++ b/vendor/code.gitea.io/git/blob.go @@ -0,0 +1,73 @@ +// 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 git + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "os" + "os/exec" +) + +// Blob represents a Git object. +type Blob struct { + repo *Repository + *TreeEntry +} + +// Data gets content of blob all at once and wrap it as io.Reader. +// This can be very slow and memory consuming for huge content. +func (b *Blob) Data() (io.Reader, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + + // Preallocate memory to save ~50% memory usage on big files. + stdout.Grow(int(b.Size() + 2048)) + + if err := b.DataPipeline(stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + return stdout, nil +} + +// DataPipeline gets content of blob and write the result or error to stdout or stderr +func (b *Blob) DataPipeline(stdout, stderr io.Writer) error { + return NewCommand("show", b.ID.String()).RunInDirPipeline(b.repo.Path, stdout, stderr) +} + +type cmdReadCloser struct { + cmd *exec.Cmd + stdout io.Reader +} + +func (c cmdReadCloser) Read(p []byte) (int, error) { + return c.stdout.Read(p) +} + +func (c cmdReadCloser) Close() error { + io.Copy(ioutil.Discard, c.stdout) + return c.cmd.Wait() +} + +// DataAsync gets a ReadCloser for the contents of a blob without reading it all. +// Calling the Close function on the result will discard all unread output. +func (b *Blob) DataAsync() (io.ReadCloser, error) { + cmd := exec.Command("git", "show", b.ID.String()) + cmd.Dir = b.repo.Path + cmd.Stderr = os.Stderr + + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, fmt.Errorf("StdoutPipe: %v", err) + } + + if err = cmd.Start(); err != nil { + return nil, fmt.Errorf("Start: %v", err) + } + + return cmdReadCloser{stdout: stdout, cmd: cmd}, nil +} diff --git a/vendor/code.gitea.io/git/command.go b/vendor/code.gitea.io/git/command.go new file mode 100644 index 0000000000000..8ca99fd6d3add --- /dev/null +++ b/vendor/code.gitea.io/git/command.go @@ -0,0 +1,134 @@ +// 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 git + +import ( + "bytes" + "context" + "fmt" + "io" + "os/exec" + "strings" + "time" +) + +var ( + // GlobalCommandArgs global command args for external package setting + GlobalCommandArgs []string + + // DefaultCommandExecutionTimeout default command execution timeout duration + DefaultCommandExecutionTimeout = 60 * time.Second +) + +// Command represents a command with its subcommands or arguments. +type Command struct { + name string + args []string +} + +func (c *Command) String() string { + if len(c.args) == 0 { + return c.name + } + return fmt.Sprintf("%s %s", c.name, strings.Join(c.args, " ")) +} + +// NewCommand creates and returns a new Git Command based on given command and arguments. +func NewCommand(args ...string) *Command { + return &Command{ + name: "git", + args: append(GlobalCommandArgs, args...), + } +} + +// AddArguments adds new argument(s) to the command. +func (c *Command) AddArguments(args ...string) *Command { + c.args = append(c.args, args...) + return c +} + +// RunInDirTimeoutPipeline executes the command in given directory with given timeout, +// it pipes stdout and stderr to given io.Writer. +func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error { + if timeout == -1 { + timeout = DefaultCommandExecutionTimeout + } + + if len(dir) == 0 { + log(c.String()) + } else { + log("%s: %v", dir, c) + } + + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + cmd := exec.CommandContext(ctx, c.name, c.args...) + cmd.Dir = dir + cmd.Stdout = stdout + cmd.Stderr = stderr + if err := cmd.Start(); err != nil { + return err + } + + if err := cmd.Wait(); err != nil { + return err + } + + return ctx.Err() +} + +// RunInDirTimeout executes the command in given directory with given timeout, +// and returns stdout in []byte and error (combined with stderr). +func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + if err := c.RunInDirTimeoutPipeline(timeout, dir, stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + + if stdout.Len() > 0 { + log("stdout:\n%s", stdout.Bytes()[:1024]) + } + return stdout.Bytes(), nil +} + +// RunInDirPipeline executes the command in given directory, +// it pipes stdout and stderr to given io.Writer. +func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error { + return c.RunInDirTimeoutPipeline(-1, dir, stdout, stderr) +} + +// RunInDirBytes executes the command in given directory +// and returns stdout in []byte and error (combined with stderr). +func (c *Command) RunInDirBytes(dir string) ([]byte, error) { + return c.RunInDirTimeout(-1, dir) +} + +// RunInDir executes the command in given directory +// and returns stdout in string and error (combined with stderr). +func (c *Command) RunInDir(dir string) (string, error) { + stdout, err := c.RunInDirTimeout(-1, dir) + if err != nil { + return "", err + } + return string(stdout), nil +} + +// RunTimeout executes the command in defualt working directory with given timeout, +// and returns stdout in string and error (combined with stderr). +func (c *Command) RunTimeout(timeout time.Duration) (string, error) { + stdout, err := c.RunInDirTimeout(timeout, "") + if err != nil { + return "", err + } + return string(stdout), nil +} + +// Run executes the command in defualt working directory +// and returns stdout in string and error (combined with stderr). +func (c *Command) Run() (string, error) { + return c.RunTimeout(-1) +} diff --git a/vendor/code.gitea.io/git/commit.go b/vendor/code.gitea.io/git/commit.go new file mode 100644 index 0000000000000..299a2381b65b6 --- /dev/null +++ b/vendor/code.gitea.io/git/commit.go @@ -0,0 +1,276 @@ +// 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 git + +import ( + "bufio" + "bytes" + "container/list" + "fmt" + "net/http" + "strconv" + "strings" +) + +// Commit represents a git commit. +type Commit struct { + Tree + ID SHA1 // The ID of this commit object + Author *Signature + Committer *Signature + CommitMessage string + Signature *CommitGPGSignature + + parents []SHA1 // SHA1 strings + submoduleCache *ObjectCache +} + +// CommitGPGSignature represents a git commit signature part. +type CommitGPGSignature struct { + Signature string + Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data +} + +// similar to https://github.com/git/git/blob/3bc53220cb2dcf709f7a027a3f526befd021d858/commit.c#L1128 +func newGPGSignatureFromCommitline(data []byte, signatureStart int) (*CommitGPGSignature, error) { + sig := new(CommitGPGSignature) + signatureEnd := bytes.LastIndex(data, []byte("-----END PGP SIGNATURE-----")) + if signatureEnd == -1 { + return nil, fmt.Errorf("end of commit signature not found") + } + sig.Signature = strings.Replace(string(data[signatureStart:signatureEnd+27]), "\n ", "\n", -1) + sig.Payload = string(data[:signatureStart-8]) + string(data[signatureEnd+27:]) + return sig, nil +} + +// Message returns the commit message. Same as retrieving CommitMessage directly. +func (c *Commit) Message() string { + return c.CommitMessage +} + +// Summary returns first line of commit message. +func (c *Commit) Summary() string { + return strings.Split(strings.TrimSpace(c.CommitMessage), "\n")[0] +} + +// ParentID returns oid of n-th parent (0-based index). +// It returns nil if no such parent exists. +func (c *Commit) ParentID(n int) (SHA1, error) { + if n >= len(c.parents) { + return SHA1{}, ErrNotExist{"", ""} + } + return c.parents[n], nil +} + +// Parent returns n-th parent (0-based index) of the commit. +func (c *Commit) Parent(n int) (*Commit, error) { + id, err := c.ParentID(n) + if err != nil { + return nil, err + } + parent, err := c.repo.getCommit(id) + if err != nil { + return nil, err + } + return parent, nil +} + +// ParentCount returns number of parents of the commit. +// 0 if this is the root commit, otherwise 1,2, etc. +func (c *Commit) ParentCount() int { + return len(c.parents) +} + +func isImageFile(data []byte) (string, bool) { + contentType := http.DetectContentType(data) + if strings.Index(contentType, "image/") != -1 { + return contentType, true + } + return contentType, false +} + +// IsImageFile is a file image type +func (c *Commit) IsImageFile(name string) bool { + blob, err := c.GetBlobByPath(name) + if err != nil { + return false + } + + dataRc, err := blob.DataAsync() + if err != nil { + return false + } + defer dataRc.Close() + buf := make([]byte, 1024) + n, _ := dataRc.Read(buf) + buf = buf[:n] + _, isImage := isImageFile(buf) + return isImage +} + +// GetCommitByPath return the commit of relative path object. +func (c *Commit) GetCommitByPath(relpath string) (*Commit, error) { + return c.repo.getCommitByPathWithID(c.ID, relpath) +} + +// AddChanges marks local changes to be ready for commit. +func AddChanges(repoPath string, all bool, files ...string) error { + cmd := NewCommand("add") + if all { + cmd.AddArguments("--all") + } + _, err := cmd.AddArguments(files...).RunInDir(repoPath) + return err +} + +// CommitChangesOptions the options when a commit created +type CommitChangesOptions struct { + Committer *Signature + Author *Signature + Message string +} + +// CommitChanges commits local changes with given committer, author and message. +// If author is nil, it will be the same as committer. +func CommitChanges(repoPath string, opts CommitChangesOptions) error { + cmd := NewCommand() + if opts.Committer != nil { + cmd.AddArguments("-c", "user.name="+opts.Committer.Name, "-c", "user.email="+opts.Committer.Email) + } + cmd.AddArguments("commit") + + if opts.Author == nil { + opts.Author = opts.Committer + } + if opts.Author != nil { + cmd.AddArguments(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email)) + } + cmd.AddArguments("-m", opts.Message) + + _, err := cmd.RunInDir(repoPath) + // No stderr but exit status 1 means nothing to commit. + if err != nil && err.Error() == "exit status 1" { + return nil + } + return err +} + +func commitsCount(repoPath, revision, relpath string) (int64, error) { + var cmd *Command + cmd = NewCommand("rev-list", "--count") + cmd.AddArguments(revision) + if len(relpath) > 0 { + cmd.AddArguments("--", relpath) + } + + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return 0, err + } + + return strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) +} + +// CommitsCount returns number of total commits of until given revision. +func CommitsCount(repoPath, revision string) (int64, error) { + return commitsCount(repoPath, revision, "") +} + +// CommitsCount returns number of total commits of until current revision. +func (c *Commit) CommitsCount() (int64, error) { + return CommitsCount(c.repo.Path, c.ID.String()) +} + +// CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize +func (c *Commit) CommitsByRange(page int) (*list.List, error) { + return c.repo.commitsByRange(c.ID, page) +} + +// CommitsBefore returns all the commits before current revision +func (c *Commit) CommitsBefore() (*list.List, error) { + return c.repo.getCommitsBefore(c.ID) +} + +// CommitsBeforeLimit returns num commits before current revision +func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error) { + return c.repo.getCommitsBeforeLimit(c.ID, num) +} + +// CommitsBeforeUntil returns the commits between commitID to current revision +func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error) { + endCommit, err := c.repo.GetCommit(commitID) + if err != nil { + return nil, err + } + return c.repo.CommitsBetween(c, endCommit) +} + +// SearchCommits returns the commits match the keyword before current revision +func (c *Commit) SearchCommits(keyword string, all bool) (*list.List, error) { + return c.repo.searchCommits(c.ID, keyword, all) +} + +// GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision +func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error) { + return c.repo.getFilesChanged(pastCommit, c.ID.String()) +} + +// GetSubModules get all the sub modules of current revision git tree +func (c *Commit) GetSubModules() (*ObjectCache, error) { + if c.submoduleCache != nil { + return c.submoduleCache, nil + } + + entry, err := c.GetTreeEntryByPath(".gitmodules") + if err != nil { + if _, ok := err.(ErrNotExist); ok { + return nil, nil + } + return nil, err + } + rd, err := entry.Blob().Data() + if err != nil { + return nil, err + } + + scanner := bufio.NewScanner(rd) + c.submoduleCache = newObjectCache() + var ismodule bool + var path string + for scanner.Scan() { + if strings.HasPrefix(scanner.Text(), "[submodule") { + ismodule = true + continue + } + if ismodule { + fields := strings.Split(scanner.Text(), "=") + k := strings.TrimSpace(fields[0]) + if k == "path" { + path = strings.TrimSpace(fields[1]) + } else if k == "url" { + c.submoduleCache.Set(path, &SubModule{path, strings.TrimSpace(fields[1])}) + ismodule = false + } + } + } + + return c.submoduleCache, nil +} + +// GetSubModule get the sub module according entryname +func (c *Commit) GetSubModule(entryname string) (*SubModule, error) { + modules, err := c.GetSubModules() + if err != nil { + return nil, err + } + + if modules != nil { + module, has := modules.Get(entryname) + if has { + return module.(*SubModule), nil + } + } + return nil, nil +} diff --git a/vendor/code.gitea.io/git/commit_archive.go b/vendor/code.gitea.io/git/commit_archive.go new file mode 100644 index 0000000000000..e13825a96283b --- /dev/null +++ b/vendor/code.gitea.io/git/commit_archive.go @@ -0,0 +1,37 @@ +// 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 git + +import ( + "fmt" + "path/filepath" + "strings" +) + +// ArchiveType archive types +type ArchiveType int + +const ( + // ZIP zip archive type + ZIP ArchiveType = iota + 1 + // TARGZ tar gz archive type + TARGZ +) + +// CreateArchive create archive content to the target path +func (c *Commit) CreateArchive(target string, archiveType ArchiveType) error { + var format string + switch archiveType { + case ZIP: + format = "zip" + case TARGZ: + format = "tar.gz" + default: + return fmt.Errorf("unknown format: %v", archiveType) + } + + _, err := NewCommand("archive", "--prefix="+filepath.Base(strings.TrimSuffix(c.repo.Path, ".git"))+"/", "--format="+format, "-o", target, c.ID.String()).RunInDir(c.repo.Path) + return err +} diff --git a/vendor/code.gitea.io/git/commit_info.go b/vendor/code.gitea.io/git/commit_info.go new file mode 100644 index 0000000000000..6b42b57c90133 --- /dev/null +++ b/vendor/code.gitea.io/git/commit_info.go @@ -0,0 +1,319 @@ +// 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 git + +import ( + "bufio" + "context" + "fmt" + "os/exec" + "path" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // parameters for searching for commit infos. If the untargeted search has + // not found any entries in the past 5 commits, and 12 or fewer entries + // remain, then we'll just let the targeted-searching threads finish off, + // and stop the untargeted search to not interfere. + deferToTargetedSearchColdStreak = 5 + deferToTargetedSearchNumRemainingEntries = 12 +) + +// getCommitsInfoState shared state while getting commit info for entries +type getCommitsInfoState struct { + lock sync.Mutex + /* read-only fields, can be read without the mutex */ + // entries and entryPaths are read-only after initialization, so they can + // safely be read without the mutex + entries []*TreeEntry + // set of filepaths to get info for + entryPaths map[string]struct{} + treePath string + headCommit *Commit + + /* mutable fields, must hold mutex to read or write */ + // map from filepath to commit + commits map[string]*Commit + // set of filepaths that have been or are being searched for in a target search + targetedPaths map[string]struct{} +} + +func (state *getCommitsInfoState) numRemainingEntries() int { + state.lock.Lock() + defer state.lock.Unlock() + return len(state.entries) - len(state.commits) +} + +// getTargetEntryPath Returns the next path for a targeted-searching thread to +// search for, or returns the empty string if nothing left to search for +func (state *getCommitsInfoState) getTargetedEntryPath() string { + var targetedEntryPath string + state.lock.Lock() + defer state.lock.Unlock() + for _, entry := range state.entries { + entryPath := path.Join(state.treePath, entry.Name()) + if _, ok := state.commits[entryPath]; ok { + continue + } else if _, ok = state.targetedPaths[entryPath]; ok { + continue + } + targetedEntryPath = entryPath + state.targetedPaths[entryPath] = struct{}{} + break + } + return targetedEntryPath +} + +// repeatedly perform targeted searches for unpopulated entries +func targetedSearch(state *getCommitsInfoState, done chan error) { + for { + entryPath := state.getTargetedEntryPath() + if len(entryPath) == 0 { + done <- nil + return + } + command := NewCommand("rev-list", "-1", state.headCommit.ID.String(), "--", entryPath) + output, err := command.RunInDir(state.headCommit.repo.Path) + if err != nil { + done <- err + return + } + id, err := NewIDFromString(strings.TrimSpace(output)) + if err != nil { + done <- err + return + } + commit, err := state.headCommit.repo.getCommit(id) + if err != nil { + done <- err + return + } + state.update(entryPath, commit) + } +} + +func initGetCommitInfoState(entries Entries, headCommit *Commit, treePath string) *getCommitsInfoState { + entryPaths := make(map[string]struct{}, len(entries)) + for _, entry := range entries { + entryPaths[path.Join(treePath, entry.Name())] = struct{}{} + } + if treePath = path.Clean(treePath); treePath == "." { + treePath = "" + } + return &getCommitsInfoState{ + entries: entries, + entryPaths: entryPaths, + commits: make(map[string]*Commit, len(entries)), + targetedPaths: make(map[string]struct{}, len(entries)), + treePath: treePath, + headCommit: headCommit, + } +} + +// GetCommitsInfo gets information of all commits that are corresponding to these entries +func (tes Entries) GetCommitsInfo(commit *Commit, treePath string) ([][]interface{}, error) { + state := initGetCommitInfoState(tes, commit, treePath) + if err := getCommitsInfo(state); err != nil { + return nil, err + } + if len(state.commits) < len(state.entryPaths) { + return nil, fmt.Errorf("could not find commits for all entries") + } + + commitsInfo := make([][]interface{}, len(tes)) + for i, entry := range tes { + commit, ok := state.commits[path.Join(treePath, entry.Name())] + if !ok { + return nil, fmt.Errorf("could not find commit for %s", entry.Name()) + } + switch entry.Type { + case ObjectCommit: + subModuleURL := "" + if subModule, err := state.headCommit.GetSubModule(entry.Name()); err != nil { + return nil, err + } else if subModule != nil { + subModuleURL = subModule.URL + } + subModuleFile := NewSubModuleFile(commit, subModuleURL, entry.ID.String()) + commitsInfo[i] = []interface{}{entry, subModuleFile} + default: + commitsInfo[i] = []interface{}{entry, commit} + } + } + return commitsInfo, nil +} + +func (state *getCommitsInfoState) cleanEntryPath(rawEntryPath string) (string, error) { + if rawEntryPath[0] == '"' { + var err error + rawEntryPath, err = strconv.Unquote(rawEntryPath) + if err != nil { + return rawEntryPath, err + } + } + var entryNameStartIndex int + if len(state.treePath) > 0 { + entryNameStartIndex = len(state.treePath) + 1 + } + + if index := strings.IndexByte(rawEntryPath[entryNameStartIndex:], '/'); index >= 0 { + return rawEntryPath[:entryNameStartIndex+index], nil + } + return rawEntryPath, nil +} + +// update report that the given path was last modified by the given commit. +// Returns whether state.commits was updated +func (state *getCommitsInfoState) update(entryPath string, commit *Commit) bool { + if _, ok := state.entryPaths[entryPath]; !ok { + return false + } + + var updated bool + state.lock.Lock() + defer state.lock.Unlock() + if _, ok := state.commits[entryPath]; !ok { + state.commits[entryPath] = commit + updated = true + } + return updated +} + +const getCommitsInfoPretty = "--pretty=format:%H %ct %s" + +func getCommitsInfo(state *getCommitsInfoState) error { + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + defer cancel() + + args := []string{"log", state.headCommit.ID.String(), getCommitsInfoPretty, "--name-status", "-c"} + if len(state.treePath) > 0 { + args = append(args, "--", state.treePath) + } + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Dir = state.headCommit.repo.Path + + readCloser, err := cmd.StdoutPipe() + if err != nil { + return err + } + + if err := cmd.Start(); err != nil { + return err + } + // it's okay to ignore the error returned by cmd.Wait(); we expect the + // subprocess to sometimes have a non-zero exit status, since we may + // prematurely close stdout, resulting in a broken pipe. + defer cmd.Wait() + + numThreads := runtime.NumCPU() + done := make(chan error, numThreads) + for i := 0; i < numThreads; i++ { + go targetedSearch(state, done) + } + + scanner := bufio.NewScanner(readCloser) + err = state.processGitLogOutput(scanner) + + // it is important that we close stdout here; if we do not close + // stdout, the subprocess will keep running, and the deffered call + // cmd.Wait() may block for a long time. + if closeErr := readCloser.Close(); closeErr != nil && err == nil { + err = closeErr + } + + for i := 0; i < numThreads; i++ { + doneErr := <-done + if doneErr != nil && err == nil { + err = doneErr + } + } + return err +} + +func (state *getCommitsInfoState) processGitLogOutput(scanner *bufio.Scanner) error { + // keep a local cache of seen paths to avoid acquiring a lock for paths + // we've already seen + seenPaths := make(map[string]struct{}, len(state.entryPaths)) + // number of consecutive commits without any finds + coldStreak := 0 + var commit *Commit + var err error + for scanner.Scan() { + line := scanner.Text() + if len(line) == 0 { // in-between commits + numRemainingEntries := state.numRemainingEntries() + if numRemainingEntries == 0 { + break + } + if coldStreak >= deferToTargetedSearchColdStreak && + numRemainingEntries <= deferToTargetedSearchNumRemainingEntries { + // stop this untargeted search, and let the targeted-search threads + // finish the work + break + } + continue + } + if line[0] >= 'A' && line[0] <= 'X' { // a file was changed by the current commit + // look for the last tab, since for copies (C) and renames (R) two + // filenames are printed: src, then dest + tabIndex := strings.LastIndexByte(line, '\t') + if tabIndex < 1 { + return fmt.Errorf("misformatted line: %s", line) + } + entryPath, err := state.cleanEntryPath(line[tabIndex+1:]) + if err != nil { + return err + } + if _, ok := seenPaths[entryPath]; !ok { + if state.update(entryPath, commit) { + coldStreak = 0 + } + seenPaths[entryPath] = struct{}{} + } + continue + } + + // a new commit + commit, err = parseCommitInfo(line) + if err != nil { + return err + } + coldStreak++ + } + return scanner.Err() +} + +// parseCommitInfo parse a commit from a line of `git log` output. Expects the +// line to be formatted according to getCommitsInfoPretty. +func parseCommitInfo(line string) (*Commit, error) { + if len(line) < 43 { + return nil, fmt.Errorf("invalid git output: %s", line) + } + ref, err := NewIDFromString(line[:40]) + if err != nil { + return nil, err + } + spaceIndex := strings.IndexByte(line[41:], ' ') + if spaceIndex < 0 { + return nil, fmt.Errorf("invalid git output: %s", line) + } + unixSeconds, err := strconv.Atoi(line[41 : 41+spaceIndex]) + if err != nil { + return nil, err + } + message := line[spaceIndex+42:] + return &Commit{ + ID: ref, + CommitMessage: message, + Committer: &Signature{ + When: time.Unix(int64(unixSeconds), 0), + }, + }, nil +} diff --git a/vendor/code.gitea.io/git/doc.go b/vendor/code.gitea.io/git/doc.go new file mode 100644 index 0000000000000..1941d285507b1 --- /dev/null +++ b/vendor/code.gitea.io/git/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 git // import "code.gitea.io/git" diff --git a/vendor/code.gitea.io/git/error.go b/vendor/code.gitea.io/git/error.go new file mode 100644 index 0000000000000..1aae5a37a2891 --- /dev/null +++ b/vendor/code.gitea.io/git/error.go @@ -0,0 +1,66 @@ +// 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 git + +import ( + "fmt" + "time" +) + +// ErrExecTimeout error when exec timed out +type ErrExecTimeout struct { + Duration time.Duration +} + +// IsErrExecTimeout if some error is ErrExecTimeout +func IsErrExecTimeout(err error) bool { + _, ok := err.(ErrExecTimeout) + return ok +} + +func (err ErrExecTimeout) Error() string { + return fmt.Sprintf("execution is timeout [duration: %v]", err.Duration) +} + +// ErrNotExist commit not exist error +type ErrNotExist struct { + ID string + RelPath string +} + +// IsErrNotExist if some error is ErrNotExist +func IsErrNotExist(err error) bool { + _, ok := err.(ErrNotExist) + return ok +} + +func (err ErrNotExist) Error() string { + return fmt.Sprintf("object does not exist [id: %s, rel_path: %s]", err.ID, err.RelPath) +} + +// ErrBadLink entry.FollowLink error +type ErrBadLink struct { + Name string + Message string +} + +func (err ErrBadLink) Error() string { + return fmt.Sprintf("%s: %s", err.Name, err.Message) +} + +// ErrUnsupportedVersion error when required git version not matched +type ErrUnsupportedVersion struct { + Required string +} + +// IsErrUnsupportedVersion if some error is ErrUnsupportedVersion +func IsErrUnsupportedVersion(err error) bool { + _, ok := err.(ErrUnsupportedVersion) + return ok +} + +func (err ErrUnsupportedVersion) Error() string { + return fmt.Sprintf("Operation requires higher version [required: %s]", err.Required) +} diff --git a/vendor/code.gitea.io/git/git.go b/vendor/code.gitea.io/git/git.go new file mode 100644 index 0000000000000..150b80fb076b8 --- /dev/null +++ b/vendor/code.gitea.io/git/git.go @@ -0,0 +1,91 @@ +// Copyright 2015 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 git + +import ( + "fmt" + "strings" + "time" + + "github.com/mcuadros/go-version" +) + +// Version return this package's current version +func Version() string { + return "0.4.2" +} + +var ( + // Debug enables verbose logging on everything. + // This should be false in case Gogs starts in SSH mode. + Debug = false + // Prefix the log prefix + Prefix = "[git-module] " + // GitVersionRequired is the minimum Git version required + GitVersionRequired = "1.7.2" +) + +func log(format string, args ...interface{}) { + if !Debug { + return + } + + fmt.Print(Prefix) + if len(args) == 0 { + fmt.Println(format) + } else { + fmt.Printf(format+"\n", args...) + } +} + +var gitVersion string + +// BinVersion returns current Git version from shell. +func BinVersion() (string, error) { + if len(gitVersion) > 0 { + return gitVersion, nil + } + + stdout, err := NewCommand("version").Run() + if err != nil { + return "", err + } + + fields := strings.Fields(stdout) + if len(fields) < 3 { + return "", fmt.Errorf("not enough output: %s", stdout) + } + + // Handle special case on Windows. + i := strings.Index(fields[2], "windows") + if i >= 1 { + gitVersion = fields[2][:i-1] + return gitVersion, nil + } + + gitVersion = fields[2] + return gitVersion, nil +} + +func init() { + gitVersion, err := BinVersion() + if err != nil { + panic(fmt.Sprintf("Git version missing: %v", err)) + } + if version.Compare(gitVersion, GitVersionRequired, "<") { + panic(fmt.Sprintf("Git version not supported. Requires version > %v", GitVersionRequired)) + } +} + +// Fsck verifies the connectivity and validity of the objects in the database +func Fsck(repoPath string, timeout time.Duration, args ...string) error { + // Make sure timeout makes sense. + if timeout <= 0 { + timeout = -1 + } + _, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath) + return err +} diff --git a/vendor/code.gitea.io/git/hook.go b/vendor/code.gitea.io/git/hook.go new file mode 100644 index 0000000000000..afed623e6eacf --- /dev/null +++ b/vendor/code.gitea.io/git/hook.go @@ -0,0 +1,126 @@ +// 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 git + +import ( + "errors" + "io/ioutil" + "os" + "path" + "path/filepath" + "strings" + + "github.com/Unknwon/com" +) + +// hookNames is a list of Git server hooks' name that are supported. +var hookNames = []string{ + "pre-receive", + "update", + "post-receive", +} + +var ( + // ErrNotValidHook error when a git hook is not valid + ErrNotValidHook = errors.New("not a valid Git hook") +) + +// IsValidHookName returns true if given name is a valid Git hook. +func IsValidHookName(name string) bool { + for _, hn := range hookNames { + if hn == name { + return true + } + } + return false +} + +// Hook represents a Git hook. +type Hook struct { + name string + IsActive bool // Indicates whether repository has this hook. + Content string // Content of hook if it's active. + Sample string // Sample content from Git. + path string // Hook file path. +} + +// GetHook returns a Git hook by given name and repository. +func GetHook(repoPath, name string) (*Hook, error) { + if !IsValidHookName(name) { + return nil, ErrNotValidHook + } + h := &Hook{ + name: name, + path: path.Join(repoPath, "hooks", name+".d", name), + } + samplePath := filepath.Join(repoPath, "hooks", name+".sample") + if isFile(h.path) { + data, err := ioutil.ReadFile(h.path) + if err != nil { + return nil, err + } + h.IsActive = true + h.Content = string(data) + } else if isFile(samplePath) { + data, err := ioutil.ReadFile(samplePath) + if err != nil { + return nil, err + } + h.Sample = string(data) + } + return h, nil +} + +// Name return the name of the hook +func (h *Hook) Name() string { + return h.name +} + +// Update updates hook settings. +func (h *Hook) Update() error { + if len(strings.TrimSpace(h.Content)) == 0 { + if isExist(h.path) { + return os.Remove(h.path) + } + return nil + } + return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm) +} + +// ListHooks returns a list of Git hooks of given repository. +func ListHooks(repoPath string) (_ []*Hook, err error) { + if !isDir(path.Join(repoPath, "hooks")) { + return nil, errors.New("hooks path does not exist") + } + + hooks := make([]*Hook, len(hookNames)) + for i, name := range hookNames { + hooks[i], err = GetHook(repoPath, name) + if err != nil { + return nil, err + } + } + return hooks, nil +} + +const ( + // HookPathUpdate hook update path + HookPathUpdate = "hooks/update" +) + +// SetUpdateHook writes given content to update hook of the reposiotry. +func SetUpdateHook(repoPath, content string) (err error) { + log("Setting update hook: %s", repoPath) + hookPath := path.Join(repoPath, HookPathUpdate) + if com.IsExist(hookPath) { + err = os.Remove(hookPath) + } else { + err = os.MkdirAll(path.Dir(hookPath), os.ModePerm) + } + if err != nil { + return err + } + return ioutil.WriteFile(hookPath, []byte(content), 0777) +} diff --git a/vendor/code.gitea.io/git/parse.go b/vendor/code.gitea.io/git/parse.go new file mode 100644 index 0000000000000..5c964f16ee5f7 --- /dev/null +++ b/vendor/code.gitea.io/git/parse.go @@ -0,0 +1,81 @@ +// 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 git + +import ( + "bytes" + "fmt" + "strconv" +) + +// ParseTreeEntries parses the output of a `git ls-tree` command. +func ParseTreeEntries(data []byte) ([]*TreeEntry, error) { + return parseTreeEntries(data, nil) +} + +func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) { + entries := make([]*TreeEntry, 0, 10) + for pos := 0; pos < len(data); { + // expect line to be of the form " \t" + entry := new(TreeEntry) + entry.ptree = ptree + if pos+6 > len(data) { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + switch string(data[pos : pos+6]) { + case "100644": + entry.mode = EntryModeBlob + entry.Type = ObjectBlob + pos += 12 // skip over "100644 blob " + case "100755": + entry.mode = EntryModeExec + entry.Type = ObjectBlob + pos += 12 // skip over "100755 blob " + case "120000": + entry.mode = EntryModeSymlink + entry.Type = ObjectBlob + pos += 12 // skip over "120000 blob " + case "160000": + entry.mode = EntryModeCommit + entry.Type = ObjectCommit + pos += 14 // skip over "160000 object " + case "040000": + entry.mode = EntryModeTree + entry.Type = ObjectTree + pos += 12 // skip over "040000 tree " + default: + return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6])) + } + + if pos+40 > len(data) { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + id, err := NewIDFromString(string(data[pos : pos+40])) + if err != nil { + return nil, fmt.Errorf("Invalid ls-tree output: %v", err) + } + entry.ID = id + pos += 41 // skip over sha and trailing space + + end := pos + bytes.IndexByte(data[pos:], '\n') + if end < pos { + return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data)) + } + + // In case entry name is surrounded by double quotes(it happens only in git-shell). + if data[pos] == '"' { + entry.name, err = strconv.Unquote(string(data[pos:end])) + if err != nil { + return nil, fmt.Errorf("Invalid ls-tree output: %v", err) + } + } else { + entry.name = string(data[pos:end]) + } + + pos = end + 1 + entries = append(entries, entry) + } + return entries, nil +} diff --git a/vendor/code.gitea.io/git/repo.go b/vendor/code.gitea.io/git/repo.go new file mode 100644 index 0000000000000..4306730920eb2 --- /dev/null +++ b/vendor/code.gitea.io/git/repo.go @@ -0,0 +1,287 @@ +// Copyright 2015 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 git + +import ( + "bytes" + "container/list" + "errors" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/Unknwon/com" +) + +// Repository represents a Git repository. +type Repository struct { + Path string + + commitCache *ObjectCache + tagCache *ObjectCache +} + +const prettyLogFormat = `--pretty=format:%H` + +func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, error) { + l := list.New() + if len(logs) == 0 { + return l, nil + } + + parts := bytes.Split(logs, []byte{'\n'}) + + for _, commitID := range parts { + commit, err := repo.GetCommit(string(commitID)) + if err != nil { + return nil, err + } + l.PushBack(commit) + } + + return l, nil +} + +// IsRepoURLAccessible checks if given repository URL is accessible. +func IsRepoURLAccessible(url string) bool { + _, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run() + if err != nil { + return false + } + return true +} + +// InitRepository initializes a new Git repository. +func InitRepository(repoPath string, bare bool) error { + os.MkdirAll(repoPath, os.ModePerm) + + cmd := NewCommand("init") + if bare { + cmd.AddArguments("--bare") + } + _, err := cmd.RunInDir(repoPath) + return err +} + +// OpenRepository opens the repository at the given path. +func OpenRepository(repoPath string) (*Repository, error) { + repoPath, err := filepath.Abs(repoPath) + if err != nil { + return nil, err + } else if !isDir(repoPath) { + return nil, errors.New("no such file or directory") + } + + return &Repository{ + Path: repoPath, + commitCache: newObjectCache(), + tagCache: newObjectCache(), + }, nil +} + +// CloneRepoOptions options when clone a repository +type CloneRepoOptions struct { + Timeout time.Duration + Mirror bool + Bare bool + Quiet bool + Branch string +} + +// Clone clones original repository to target path. +func Clone(from, to string, opts CloneRepoOptions) (err error) { + toDir := path.Dir(to) + if err = os.MkdirAll(toDir, os.ModePerm); err != nil { + return err + } + + cmd := NewCommand("clone") + if opts.Mirror { + cmd.AddArguments("--mirror") + } + if opts.Bare { + cmd.AddArguments("--bare") + } + if opts.Quiet { + cmd.AddArguments("--quiet") + } + if len(opts.Branch) > 0 { + cmd.AddArguments("-b", opts.Branch) + } + cmd.AddArguments(from, to) + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + _, err = cmd.RunTimeout(opts.Timeout) + return err +} + +// PullRemoteOptions options when pull from remote +type PullRemoteOptions struct { + Timeout time.Duration + All bool + Rebase bool + Remote string + Branch string +} + +// Pull pulls changes from remotes. +func Pull(repoPath string, opts PullRemoteOptions) error { + cmd := NewCommand("pull") + if opts.Rebase { + cmd.AddArguments("--rebase") + } + if opts.All { + cmd.AddArguments("--all") + } else { + cmd.AddArguments(opts.Remote) + cmd.AddArguments(opts.Branch) + } + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) + return err +} + +// PushOptions options when push to remote +type PushOptions struct { + Remote string + Branch string + Force bool +} + +// Push pushs local commits to given remote branch. +func Push(repoPath string, opts PushOptions) error { + cmd := NewCommand("push") + if opts.Force { + cmd.AddArguments("-f") + } + cmd.AddArguments(opts.Remote, opts.Branch) + _, err := cmd.RunInDir(repoPath) + return err +} + +// CheckoutOptions options when heck out some branch +type CheckoutOptions struct { + Timeout time.Duration + Branch string + OldBranch string +} + +// Checkout checkouts a branch +func Checkout(repoPath string, opts CheckoutOptions) error { + cmd := NewCommand("checkout") + if len(opts.OldBranch) > 0 { + cmd.AddArguments("-b") + } + + if opts.Timeout <= 0 { + opts.Timeout = -1 + } + + cmd.AddArguments(opts.Branch) + + if len(opts.OldBranch) > 0 { + cmd.AddArguments(opts.OldBranch) + } + + _, err := cmd.RunInDirTimeout(opts.Timeout, repoPath) + return err +} + +// ResetHEAD resets HEAD to given revision or head of branch. +func ResetHEAD(repoPath string, hard bool, revision string) error { + cmd := NewCommand("reset") + if hard { + cmd.AddArguments("--hard") + } + _, err := cmd.AddArguments(revision).RunInDir(repoPath) + return err +} + +// MoveFile moves a file to another file or directory. +func MoveFile(repoPath, oldTreeName, newTreeName string) error { + _, err := NewCommand("mv").AddArguments(oldTreeName, newTreeName).RunInDir(repoPath) + return err +} + +// CountObject represents repository count objects report +type CountObject struct { + Count int64 + Size int64 + InPack int64 + Packs int64 + SizePack int64 + PrunePack int64 + Garbage int64 + SizeGarbage int64 +} + +const ( + statCount = "count: " + statSize = "size: " + statInpack = "in-pack: " + statPacks = "packs: " + statSizePack = "size-pack: " + statPrunePackage = "prune-package: " + statGarbage = "garbage: " + statSizeGarbage = "size-garbage: " +) + +// GetRepoSize returns disk consumption for repo in path +func GetRepoSize(repoPath string) (*CountObject, error) { + cmd := NewCommand("count-objects", "-v") + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return nil, err + } + + return parseSize(stdout), nil +} + +// parseSize parses the output from count-objects and return a CountObject +func parseSize(objects string) *CountObject { + repoSize := new(CountObject) + for _, line := range strings.Split(objects, "\n") { + switch { + case strings.HasPrefix(line, statCount): + repoSize.Count = com.StrTo(line[7:]).MustInt64() + case strings.HasPrefix(line, statSize): + repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024 + case strings.HasPrefix(line, statInpack): + repoSize.InPack = com.StrTo(line[9:]).MustInt64() + case strings.HasPrefix(line, statPacks): + repoSize.Packs = com.StrTo(line[7:]).MustInt64() + case strings.HasPrefix(line, statSizePack): + repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024 + case strings.HasPrefix(line, statPrunePackage): + repoSize.PrunePack = com.StrTo(line[16:]).MustInt64() + case strings.HasPrefix(line, statGarbage): + repoSize.Garbage = com.StrTo(line[9:]).MustInt64() + case strings.HasPrefix(line, statSizeGarbage): + repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024 + } + } + return repoSize +} + +// GetLatestCommitTime returns time for latest commit in repository (across all branches) +func GetLatestCommitTime(repoPath string) (time.Time, error) { + cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)") + stdout, err := cmd.RunInDir(repoPath) + if err != nil { + return time.Time{}, err + } + commitTime := strings.TrimSpace(stdout) + return time.Parse(GitTimeLayout, commitTime) +} diff --git a/vendor/code.gitea.io/git/repo_blame.go b/vendor/code.gitea.io/git/repo_blame.go new file mode 100644 index 0000000000000..80ec50e4723cf --- /dev/null +++ b/vendor/code.gitea.io/git/repo_blame.go @@ -0,0 +1,24 @@ +// 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 git + +import "fmt" + +// FileBlame return the Blame object of file +func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { + return NewCommand("blame", "--root", "--", file).RunInDirBytes(path) +} + +// LineBlame returns the latest commit at the given line +func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { + res, err := NewCommand("blame", fmt.Sprintf("-L %d,%d", line, line), "-p", revision, "--", file).RunInDir(path) + if err != nil { + return nil, err + } + if len(res) < 40 { + return nil, fmt.Errorf("invalid result of blame: %s", res) + } + return repo.GetCommit(string(res[:40])) +} diff --git a/vendor/code.gitea.io/git/repo_branch.go b/vendor/code.gitea.io/git/repo_branch.go new file mode 100644 index 0000000000000..3b50eece14a31 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_branch.go @@ -0,0 +1,123 @@ +// 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 git + +import ( + "fmt" + "strings" +) + +// BranchPrefix base dir of the branch information file store on git +const BranchPrefix = "refs/heads/" + +// IsReferenceExist returns true if given reference exists in the repository. +func IsReferenceExist(repoPath, name string) bool { + _, err := NewCommand("show-ref", "--verify", name).RunInDir(repoPath) + return err == nil +} + +// IsBranchExist returns true if given branch exists in the repository. +func IsBranchExist(repoPath, name string) bool { + return IsReferenceExist(repoPath, BranchPrefix+name) +} + +// IsBranchExist returns true if given branch exists in current repository. +func (repo *Repository) IsBranchExist(name string) bool { + return IsBranchExist(repo.Path, name) +} + +// Branch represents a Git branch. +type Branch struct { + Name string + Path string +} + +// GetHEADBranch returns corresponding branch of HEAD. +func (repo *Repository) GetHEADBranch() (*Branch, error) { + stdout, err := NewCommand("symbolic-ref", "HEAD").RunInDir(repo.Path) + if err != nil { + return nil, err + } + stdout = strings.TrimSpace(stdout) + + if !strings.HasPrefix(stdout, BranchPrefix) { + return nil, fmt.Errorf("invalid HEAD branch: %v", stdout) + } + + return &Branch{ + Name: stdout[len(BranchPrefix):], + Path: stdout, + }, nil +} + +// SetDefaultBranch sets default branch of repository. +func (repo *Repository) SetDefaultBranch(name string) error { + _, err := NewCommand("symbolic-ref", "HEAD", BranchPrefix+name).RunInDir(repo.Path) + return err +} + +// GetBranches returns all branches of the repository. +func (repo *Repository) GetBranches() ([]string, error) { + stdout, err := NewCommand("for-each-ref", "--format=%(refname)", BranchPrefix).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + refs := strings.Split(stdout, "\n") + branches := make([]string, len(refs)-1) + for i, ref := range refs[:len(refs)-1] { + branches[i] = strings.TrimPrefix(ref, BranchPrefix) + } + return branches, nil +} + +// DeleteBranchOptions Option(s) for delete branch +type DeleteBranchOptions struct { + Force bool +} + +// DeleteBranch delete a branch by name on repository. +func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error { + cmd := NewCommand("branch") + + if opts.Force { + cmd.AddArguments("-D") + } else { + cmd.AddArguments("-d") + } + + cmd.AddArguments(name) + _, err := cmd.RunInDir(repo.Path) + + return err +} + +// CreateBranch create a new branch +func (repo *Repository) CreateBranch(branch, newBranch string) error { + cmd := NewCommand("branch") + cmd.AddArguments(branch, newBranch) + + _, err := cmd.RunInDir(repo.Path) + + return err +} + +// AddRemote adds a new remote to repository. +func (repo *Repository) AddRemote(name, url string, fetch bool) error { + cmd := NewCommand("remote", "add") + if fetch { + cmd.AddArguments("-f") + } + cmd.AddArguments(name, url) + + _, err := cmd.RunInDir(repo.Path) + return err +} + +// RemoveRemote removes a remote from repository. +func (repo *Repository) RemoveRemote(name string) error { + _, err := NewCommand("remote", "remove", name).RunInDir(repo.Path) + return err +} diff --git a/vendor/code.gitea.io/git/repo_commit.go b/vendor/code.gitea.io/git/repo_commit.go new file mode 100644 index 0000000000000..1acdfffb34738 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_commit.go @@ -0,0 +1,352 @@ +// 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 git + +import ( + "bytes" + "container/list" + "strconv" + "strings" + + "github.com/mcuadros/go-version" +) + +// GetRefCommitID returns the last commit ID string of given reference (branch or tag). +func (repo *Repository) GetRefCommitID(name string) (string, error) { + stdout, err := NewCommand("show-ref", "--verify", name).RunInDir(repo.Path) + if err != nil { + if strings.Contains(err.Error(), "not a valid ref") { + return "", ErrNotExist{name, ""} + } + return "", err + } + return strings.Split(stdout, " ")[0], nil +} + +// GetBranchCommitID returns last commit ID string of given branch. +func (repo *Repository) GetBranchCommitID(name string) (string, error) { + return repo.GetRefCommitID(BranchPrefix + name) +} + +// GetTagCommitID returns last commit ID string of given tag. +func (repo *Repository) GetTagCommitID(name string) (string, error) { + return repo.GetRefCommitID(TagPrefix + name) +} + +// parseCommitData parses commit information from the (uncompressed) raw +// data from the commit object. +// \n\n separate headers from message +func parseCommitData(data []byte) (*Commit, error) { + commit := new(Commit) + commit.parents = make([]SHA1, 0, 1) + // we now have the contents of the commit object. Let's investigate... + nextline := 0 +l: + for { + eol := bytes.IndexByte(data[nextline:], '\n') + switch { + case eol > 0: + line := data[nextline : nextline+eol] + spacepos := bytes.IndexByte(line, ' ') + reftype := line[:spacepos] + switch string(reftype) { + case "tree", "object": + id, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + commit.Tree.ID = id + case "parent": + // A commit can have one or more parents + oid, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + commit.parents = append(commit.parents, oid) + case "author", "tagger": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + commit.Author = sig + case "committer": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + commit.Committer = sig + case "gpgsig": + sig, err := newGPGSignatureFromCommitline(data, nextline+spacepos+1) + if err != nil { + return nil, err + } + commit.Signature = sig + } + nextline += eol + 1 + case eol == 0: + commit.CommitMessage = string(data[nextline+1:]) + break l + default: + break l + } + } + return commit, nil +} + +func (repo *Repository) getCommit(id SHA1) (*Commit, error) { + c, ok := repo.commitCache.Get(id.String()) + if ok { + log("Hit cache: %s", id) + return c.(*Commit), nil + } + + data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) + if err != nil { + if strings.Contains(err.Error(), "fatal: Not a valid object name") { + return nil, ErrNotExist{id.String(), ""} + } + return nil, err + } + + commit, err := parseCommitData(data) + if err != nil { + return nil, err + } + commit.repo = repo + commit.ID = id + + repo.commitCache.Set(id.String(), commit) + return commit, nil +} + +// GetCommit returns commit object of by ID string. +func (repo *Repository) GetCommit(commitID string) (*Commit, error) { + if len(commitID) != 40 { + var err error + commitID, err = NewCommand("rev-parse", commitID).RunInDir(repo.Path) + if err != nil { + return nil, err + } + } + id, err := NewIDFromString(commitID) + if err != nil { + return nil, err + } + + return repo.getCommit(id) +} + +// GetBranchCommit returns the last commit of given branch. +func (repo *Repository) GetBranchCommit(name string) (*Commit, error) { + commitID, err := repo.GetBranchCommitID(name) + if err != nil { + return nil, err + } + return repo.GetCommit(commitID) +} + +// GetTagCommit get the commit of the specific tag via name +func (repo *Repository) GetTagCommit(name string) (*Commit, error) { + commitID, err := repo.GetTagCommitID(name) + if err != nil { + return nil, err + } + return repo.GetCommit(commitID) +} + +func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, error) { + // File name starts with ':' must be escaped. + if relpath[0] == ':' { + relpath = `\` + relpath + } + + stdout, err := NewCommand("log", "-1", prettyLogFormat, id.String(), "--", relpath).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + id, err = NewIDFromString(stdout) + if err != nil { + return nil, err + } + + return repo.getCommit(id) +} + +// GetCommitByPath returns the last commit of relative path. +func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { + stdout, err := NewCommand("log", "-1", prettyLogFormat, "--", relpath).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + commits, err := repo.parsePrettyFormatLogToList(stdout) + if err != nil { + return nil, err + } + return commits.Front().Value.(*Commit), nil +} + +// CommitsRangeSize the default commits range size +var CommitsRangeSize = 50 + +func (repo *Repository) commitsByRange(id SHA1, page int) (*list.List, error) { + stdout, err := NewCommand("log", id.String(), "--skip="+strconv.Itoa((page-1)*CommitsRangeSize), + "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +func (repo *Repository) searchCommits(id SHA1, keyword string, all bool) (*list.List, error) { + cmd := NewCommand("log", id.String(), "-100", "-i", "--grep="+keyword, prettyLogFormat) + if all { + cmd.AddArguments("--all") + } + stdout, err := cmd.RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +func (repo *Repository) getFilesChanged(id1 string, id2 string) ([]string, error) { + stdout, err := NewCommand("diff", "--name-only", id1, id2).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return strings.Split(string(stdout), "\n"), nil +} + +// FileCommitsCount return the number of files at a revison +func (repo *Repository) FileCommitsCount(revision, file string) (int64, error) { + return commitsCount(repo.Path, revision, file) +} + +// CommitsByFileAndRange return the commits accroding revison file and the page +func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error) { + stdout, err := NewCommand("log", revision, "--follow", "--skip="+strconv.Itoa((page-1)*50), + "--max-count="+strconv.Itoa(CommitsRangeSize), prettyLogFormat, "--", file).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(stdout) +} + +// FilesCountBetween return the number of files changed between two commits +func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { + stdout, err := NewCommand("diff", "--name-only", startCommitID+"..."+endCommitID).RunInDir(repo.Path) + if err != nil { + return 0, err + } + return len(strings.Split(stdout, "\n")) - 1, nil +} + +// CommitsBetween returns a list that contains commits between [last, before). +func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error) { + stdout, err := NewCommand("rev-list", before.ID.String()+"..."+last.ID.String()).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + return repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) +} + +// CommitsBetweenIDs return commits between twoe commits +func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error) { + lastCommit, err := repo.GetCommit(last) + if err != nil { + return nil, err + } + beforeCommit, err := repo.GetCommit(before) + if err != nil { + return nil, err + } + return repo.CommitsBetween(lastCommit, beforeCommit) +} + +// CommitsCountBetween return numbers of commits between two commits +func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) { + return commitsCount(repo.Path, start+"..."+end, "") +} + +// commitsBefore the limit is depth, not total number of returned commits. +func (repo *Repository) commitsBefore(id SHA1, limit int) (*list.List, error) { + cmd := NewCommand("log") + if limit > 0 { + cmd.AddArguments("-"+strconv.Itoa(limit), prettyLogFormat, id.String()) + } else { + cmd.AddArguments(prettyLogFormat, id.String()) + } + + stdout, err := cmd.RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + formattedLog, err := repo.parsePrettyFormatLogToList(bytes.TrimSpace(stdout)) + if err != nil { + return nil, err + } + + commits := list.New() + for logEntry := formattedLog.Front(); logEntry != nil; logEntry = logEntry.Next() { + commit := logEntry.Value.(*Commit) + branches, err := repo.getBranches(commit, 2) + if err != nil { + return nil, err + } + + if len(branches) > 1 { + break + } + + commits.PushBack(commit) + } + + return commits, nil +} + +func (repo *Repository) getCommitsBefore(id SHA1) (*list.List, error) { + return repo.commitsBefore(id, 0) +} + +func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) (*list.List, error) { + return repo.commitsBefore(id, num) +} + +func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) { + if version.Compare(gitVersion, "2.7.0", ">=") { + stdout, err := NewCommand("for-each-ref", "--count="+strconv.Itoa(limit), "--format=%(refname:strip=2)", "--contains", commit.ID.String(), BranchPrefix).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + branches := strings.Fields(stdout) + return branches, nil + } + + stdout, err := NewCommand("branch", "--contains", commit.ID.String()).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + refs := strings.Split(stdout, "\n") + + var max int + if len(refs) > limit { + max = limit + } else { + max = len(refs) - 1 + } + + branches := make([]string, max) + for i, ref := range refs[:max] { + parts := strings.Fields(ref) + + branches[i] = parts[len(parts)-1] + } + return branches, nil +} diff --git a/vendor/code.gitea.io/git/repo_hook.go b/vendor/code.gitea.io/git/repo_hook.go new file mode 100644 index 0000000000000..49f4d09fb685b --- /dev/null +++ b/vendor/code.gitea.io/git/repo_hook.go @@ -0,0 +1,15 @@ +// 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 git + +// GetHook get one hook accroding the name on a repository +func (repo *Repository) GetHook(name string) (*Hook, error) { + return GetHook(repo.Path, name) +} + +// Hooks get all the hooks on the repository +func (repo *Repository) Hooks() ([]*Hook, error) { + return ListHooks(repo.Path) +} diff --git a/vendor/code.gitea.io/git/repo_object.go b/vendor/code.gitea.io/git/repo_object.go new file mode 100644 index 0000000000000..3be8400d22210 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_object.go @@ -0,0 +1,19 @@ +// 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 git + +// ObjectType git object type +type ObjectType string + +const ( + // ObjectCommit commit object type + ObjectCommit ObjectType = "commit" + // ObjectTree tree object type + ObjectTree ObjectType = "tree" + // ObjectBlob blob object type + ObjectBlob ObjectType = "blob" + // ObjectTag tag object type + ObjectTag ObjectType = "tag" +) diff --git a/vendor/code.gitea.io/git/repo_pull.go b/vendor/code.gitea.io/git/repo_pull.go new file mode 100644 index 0000000000000..c6d97a6fd167d --- /dev/null +++ b/vendor/code.gitea.io/git/repo_pull.go @@ -0,0 +1,89 @@ +// 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 git + +import ( + "bytes" + "container/list" + "fmt" + "io" + "strconv" + "strings" + "time" +) + +// PullRequestInfo represents needed information for a pull request. +type PullRequestInfo struct { + MergeBase string + Commits *list.List + NumFiles int +} + +// GetMergeBase checks and returns merge base of two branches. +func (repo *Repository) GetMergeBase(base, head string) (string, error) { + stdout, err := NewCommand("merge-base", base, head).RunInDir(repo.Path) + return strings.TrimSpace(stdout), err +} + +// GetPullRequestInfo generates and returns pull request information +// between base and head branches of repositories. +func (repo *Repository) GetPullRequestInfo(basePath, baseBranch, headBranch string) (_ *PullRequestInfo, err error) { + var remoteBranch string + + // We don't need a temporary remote for same repository. + if repo.Path != basePath { + // Add a temporary remote + tmpRemote := strconv.FormatInt(time.Now().UnixNano(), 10) + if err = repo.AddRemote(tmpRemote, basePath, true); err != nil { + return nil, fmt.Errorf("AddRemote: %v", err) + } + defer repo.RemoveRemote(tmpRemote) + + remoteBranch = "remotes/" + tmpRemote + "/" + baseBranch + } else { + remoteBranch = baseBranch + } + + prInfo := new(PullRequestInfo) + prInfo.MergeBase, err = repo.GetMergeBase(remoteBranch, headBranch) + if err != nil { + return nil, fmt.Errorf("GetMergeBase: %v", err) + } + + logs, err := NewCommand("log", prInfo.MergeBase+"..."+headBranch, prettyLogFormat).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + prInfo.Commits, err = repo.parsePrettyFormatLogToList(logs) + if err != nil { + return nil, fmt.Errorf("parsePrettyFormatLogToList: %v", err) + } + + // Count number of changed files. + stdout, err := NewCommand("diff", "--name-only", remoteBranch+"..."+headBranch).RunInDir(repo.Path) + if err != nil { + return nil, err + } + prInfo.NumFiles = len(strings.Split(stdout, "\n")) - 1 + + return prInfo, nil +} + +// GetPatch generates and returns patch data between given revisions. +func (repo *Repository) GetPatch(base, head string) ([]byte, error) { + return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path) +} + +// GetFormatPatch generates and returns format-patch data between given revisions. +func (repo *Repository) GetFormatPatch(base, head string) (io.Reader, error) { + stdout := new(bytes.Buffer) + stderr := new(bytes.Buffer) + + if err := NewCommand("format-patch", "--binary", "--stdout", base+"..."+head). + RunInDirPipeline(repo.Path, stdout, stderr); err != nil { + return nil, concatenateError(err, stderr.String()) + } + return stdout, nil +} diff --git a/vendor/code.gitea.io/git/repo_tag.go b/vendor/code.gitea.io/git/repo_tag.go new file mode 100644 index 0000000000000..11f1f3da73af9 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_tag.go @@ -0,0 +1,157 @@ +// 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 git + +import ( + "strings" + + "github.com/mcuadros/go-version" +) + +// TagPrefix tags prefix path on the repository +const TagPrefix = "refs/tags/" + +// IsTagExist returns true if given tag exists in the repository. +func IsTagExist(repoPath, name string) bool { + return IsReferenceExist(repoPath, TagPrefix+name) +} + +// IsTagExist returns true if given tag exists in the repository. +func (repo *Repository) IsTagExist(name string) bool { + return IsTagExist(repo.Path, name) +} + +// CreateTag create one tag in the repository +func (repo *Repository) CreateTag(name, revision string) error { + _, err := NewCommand("tag", name, revision).RunInDir(repo.Path) + return err +} + +func (repo *Repository) getTag(id SHA1) (*Tag, error) { + t, ok := repo.tagCache.Get(id.String()) + if ok { + log("Hit cache: %s", id) + return t.(*Tag), nil + } + + // Get tag type + tp, err := NewCommand("cat-file", "-t", id.String()).RunInDir(repo.Path) + if err != nil { + return nil, err + } + tp = strings.TrimSpace(tp) + + // Tag is a commit. + if ObjectType(tp) == ObjectCommit { + tag := &Tag{ + ID: id, + Object: id, + Type: string(ObjectCommit), + repo: repo, + } + + repo.tagCache.Set(id.String(), tag) + return tag, nil + } + + // Tag with message. + data, err := NewCommand("cat-file", "-p", id.String()).RunInDirBytes(repo.Path) + if err != nil { + return nil, err + } + + tag, err := parseTagData(data) + if err != nil { + return nil, err + } + + tag.ID = id + tag.repo = repo + + repo.tagCache.Set(id.String(), tag) + return tag, nil +} + +// GetTag returns a Git tag by given name. +func (repo *Repository) GetTag(name string) (*Tag, error) { + stdout, err := NewCommand("show-ref", "--tags", name).RunInDir(repo.Path) + if err != nil { + return nil, err + } + + id, err := NewIDFromString(strings.Split(stdout, " ")[0]) + if err != nil { + return nil, err + } + + tag, err := repo.getTag(id) + if err != nil { + return nil, err + } + tag.Name = name + return tag, nil +} + +// GetTagInfos returns all tag infos of the repository. +func (repo *Repository) GetTagInfos() ([]*Tag, error) { + // TODO this a slow implementation, makes one git command per tag + stdout, err := NewCommand("tag").RunInDir(repo.Path) + if err != nil { + return nil, err + } + + tagNames := strings.Split(stdout, "\n") + var tags []*Tag + for _, tagName := range tagNames { + tagName = strings.TrimSpace(tagName) + if len(tagName) == 0 { + continue + } + commitID, err := NewCommand("rev-parse", tagName).RunInDir(repo.Path) + if err != nil { + return nil, err + } + commit, err := repo.GetCommit(commitID) + if err != nil { + return nil, err + } + tags = append(tags, &Tag{ + Name: tagName, + Message: commit.Message(), + Object: commit.ID, + Tagger: commit.Author, + }) + } + sortTagsByTime(tags) + return tags, nil +} + +// GetTags returns all tags of the repository. +func (repo *Repository) GetTags() ([]string, error) { + cmd := NewCommand("tag", "-l") + if version.Compare(gitVersion, "2.0.0", ">=") { + cmd.AddArguments("--sort=-v:refname") + } + + stdout, err := cmd.RunInDir(repo.Path) + if err != nil { + return nil, err + } + + tags := strings.Split(stdout, "\n") + tags = tags[:len(tags)-1] + + if version.Compare(gitVersion, "2.0.0", "<") { + version.Sort(tags) + + // Reverse order + for i := 0; i < len(tags)/2; i++ { + j := len(tags) - i - 1 + tags[i], tags[j] = tags[j], tags[i] + } + } + + return tags, nil +} diff --git a/vendor/code.gitea.io/git/repo_tree.go b/vendor/code.gitea.io/git/repo_tree.go new file mode 100644 index 0000000000000..6e3843f7e5389 --- /dev/null +++ b/vendor/code.gitea.io/git/repo_tree.go @@ -0,0 +1,26 @@ +// 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 git + +func (repo *Repository) getTree(id SHA1) (*Tree, error) { + treePath := filepathFromSHA1(repo.Path, id.String()) + if isFile(treePath) { + _, err := NewCommand("ls-tree", id.String()).RunInDir(repo.Path) + if err != nil { + return nil, ErrNotExist{id.String(), ""} + } + } + + return NewTree(repo, id), nil +} + +// GetTree find the tree object in the repository. +func (repo *Repository) GetTree(idStr string) (*Tree, error) { + id, err := NewIDFromString(idStr) + if err != nil { + return nil, err + } + return repo.getTree(id) +} diff --git a/vendor/code.gitea.io/git/sha1.go b/vendor/code.gitea.io/git/sha1.go new file mode 100644 index 0000000000000..6c9d53949dff9 --- /dev/null +++ b/vendor/code.gitea.io/git/sha1.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 git + +import ( + "bytes" + "encoding/hex" + "fmt" + "strings" +) + +// EmptySHA defines empty git SHA +const EmptySHA = "0000000000000000000000000000000000000000" + +// SHA1 a git commit name +type SHA1 [20]byte + +// Equal returns true if s has the same SHA1 as caller. +// Support 40-length-string, []byte, SHA1. +func (id SHA1) Equal(s2 interface{}) bool { + switch v := s2.(type) { + case string: + if len(v) != 40 { + return false + } + return v == id.String() + case []byte: + return bytes.Equal(v, id[:]) + case SHA1: + return v == id + default: + return false + } +} + +// String returns string (hex) representation of the Oid. +func (id SHA1) String() string { + return hex.EncodeToString(id[:]) +} + +// MustID always creates a new SHA1 from a [20]byte array with no validation of input. +func MustID(b []byte) SHA1 { + var id SHA1 + copy(id[:], b) + return id +} + +// NewID creates a new SHA1 from a [20]byte array. +func NewID(b []byte) (SHA1, error) { + if len(b) != 20 { + return SHA1{}, fmt.Errorf("Length must be 20: %v", b) + } + return MustID(b), nil +} + +// MustIDFromString always creates a new sha from a ID with no validation of input. +func MustIDFromString(s string) SHA1 { + b, _ := hex.DecodeString(s) + return MustID(b) +} + +// NewIDFromString creates a new SHA1 from a ID string of length 40. +func NewIDFromString(s string) (SHA1, error) { + var id SHA1 + s = strings.TrimSpace(s) + if len(s) != 40 { + return id, fmt.Errorf("Length must be 40: %s", s) + } + b, err := hex.DecodeString(s) + if err != nil { + return id, err + } + return NewID(b) +} diff --git a/vendor/code.gitea.io/git/signature.go b/vendor/code.gitea.io/git/signature.go new file mode 100644 index 0000000000000..e6ab247fd73fa --- /dev/null +++ b/vendor/code.gitea.io/git/signature.go @@ -0,0 +1,58 @@ +// 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 git + +import ( + "bytes" + "strconv" + "time" +) + +// Signature represents the Author or Committer information. +type Signature struct { + Email string + Name string + When time.Time +} + +const ( + // GitTimeLayout is the (default) time layout used by git. + GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700" +) + +// Helper to get a signature from the commit line, which looks like these: +// author Patrick Gundlach 1378823654 +0200 +// author Patrick Gundlach Thu, 07 Apr 2005 22:13:13 +0200 +// but without the "author " at the beginning (this method should) +// be used for author and committer. +// +// FIXME: include timezone for timestamp! +func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { + sig := new(Signature) + emailStart := bytes.IndexByte(line, '<') + sig.Name = string(line[:emailStart-1]) + emailEnd := bytes.IndexByte(line, '>') + sig.Email = string(line[emailStart+1 : emailEnd]) + + // Check date format. + if len(line) > emailEnd+2 { + firstChar := line[emailEnd+2] + if firstChar >= 48 && firstChar <= 57 { + timestop := bytes.IndexByte(line[emailEnd+2:], ' ') + timestring := string(line[emailEnd+2 : emailEnd+2+timestop]) + seconds, _ := strconv.ParseInt(timestring, 10, 64) + sig.When = time.Unix(seconds, 0) + } else { + sig.When, err = time.Parse(GitTimeLayout, string(line[emailEnd+2:])) + if err != nil { + return nil, err + } + } + } else { + // Fall back to unix 0 time + sig.When = time.Unix(0, 0) + } + return sig, nil +} diff --git a/vendor/code.gitea.io/git/submodule.go b/vendor/code.gitea.io/git/submodule.go new file mode 100644 index 0000000000000..a0fe7b4a5691c --- /dev/null +++ b/vendor/code.gitea.io/git/submodule.go @@ -0,0 +1,79 @@ +// 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 git + +import "strings" + +// SubModule submodule is a reference on git repository +type SubModule struct { + Name string + URL string +} + +// SubModuleFile represents a file with submodule type. +type SubModuleFile struct { + *Commit + + refURL string + refID string +} + +// NewSubModuleFile create a new submodule file +func NewSubModuleFile(c *Commit, refURL, refID string) *SubModuleFile { + return &SubModuleFile{ + Commit: c, + refURL: refURL, + refID: refID, + } +} + +// RefURL guesses and returns reference URL. +func (sf *SubModuleFile) RefURL(urlPrefix string, parentPath string) string { + if sf.refURL == "" { + return "" + } + + url := strings.TrimSuffix(sf.refURL, ".git") + + // git://xxx/user/repo + if strings.HasPrefix(url, "git://") { + return "http://" + strings.TrimPrefix(url, "git://") + } + + // http[s]://xxx/user/repo + if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") { + return url + } + + // Relative url prefix check (according to git submodule documentation) + if strings.HasPrefix(url, "./") || strings.HasPrefix(url, "../") { + // ...construct and return correct submodule url here... + idx := strings.Index(parentPath, "/src/") + if idx == -1 { + return url + } + return strings.TrimSuffix(urlPrefix, "/") + parentPath[:idx] + "/" + url + } + + // sysuser@xxx:user/repo + i := strings.Index(url, "@") + j := strings.LastIndex(url, ":") + + // Only process when i < j because git+ssh://git@git.forwardbias.in/npploader.git + if i > -1 && j > -1 && i < j { + // fix problem with reverse proxy works only with local server + if strings.Contains(urlPrefix, url[i+1:j]) { + return urlPrefix + url[j+1:] + } + return "http://" + url[i+1:j] + "/" + url[j+1:] + } + + return url +} + +// RefID returns reference ID. +func (sf *SubModuleFile) RefID() string { + return sf.refID +} diff --git a/vendor/code.gitea.io/git/tag.go b/vendor/code.gitea.io/git/tag.go new file mode 100644 index 0000000000000..500fd274914c4 --- /dev/null +++ b/vendor/code.gitea.io/git/tag.go @@ -0,0 +1,89 @@ +// 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 git + +import ( + "bytes" + "sort" +) + +// Tag represents a Git tag. +type Tag struct { + Name string + ID SHA1 + repo *Repository + Object SHA1 // The id of this commit object + Type string + Tagger *Signature + Message string +} + +// Commit return the commit of the tag reference +func (tag *Tag) Commit() (*Commit, error) { + return tag.repo.getCommit(tag.Object) +} + +// Parse commit information from the (uncompressed) raw +// data from the commit object. +// \n\n separate headers from message +func parseTagData(data []byte) (*Tag, error) { + tag := new(Tag) + // we now have the contents of the commit object. Let's investigate... + nextline := 0 +l: + for { + eol := bytes.IndexByte(data[nextline:], '\n') + switch { + case eol > 0: + line := data[nextline : nextline+eol] + spacepos := bytes.IndexByte(line, ' ') + reftype := line[:spacepos] + switch string(reftype) { + case "object": + id, err := NewIDFromString(string(line[spacepos+1:])) + if err != nil { + return nil, err + } + tag.Object = id + case "type": + // A commit can have one or more parents + tag.Type = string(line[spacepos+1:]) + case "tagger": + sig, err := newSignatureFromCommitline(line[spacepos+1:]) + if err != nil { + return nil, err + } + tag.Tagger = sig + } + nextline += eol + 1 + case eol == 0: + tag.Message = string(data[nextline+1:]) + break l + default: + break l + } + } + return tag, nil +} + +type tagSorter []*Tag + +func (ts tagSorter) Len() int { + return len([]*Tag(ts)) +} + +func (ts tagSorter) Less(i, j int) bool { + return []*Tag(ts)[i].Tagger.When.After([]*Tag(ts)[j].Tagger.When) +} + +func (ts tagSorter) Swap(i, j int) { + []*Tag(ts)[i], []*Tag(ts)[j] = []*Tag(ts)[j], []*Tag(ts)[i] +} + +// sortTagsByTime +func sortTagsByTime(tags []*Tag) { + sorter := tagSorter(tags) + sort.Sort(sorter) +} diff --git a/vendor/code.gitea.io/git/tree.go b/vendor/code.gitea.io/git/tree.go new file mode 100644 index 0000000000000..4654dac30ea7c --- /dev/null +++ b/vendor/code.gitea.io/git/tree.go @@ -0,0 +1,72 @@ +// 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 git + +import ( + "strings" +) + +// Tree represents a flat directory listing. +type Tree struct { + ID SHA1 + repo *Repository + + // parent tree + ptree *Tree + + entries Entries + entriesParsed bool +} + +// NewTree create a new tree according the repository and commit id +func NewTree(repo *Repository, id SHA1) *Tree { + return &Tree{ + ID: id, + repo: repo, + } +} + +// SubTree get a sub tree by the sub dir path +func (t *Tree) SubTree(rpath string) (*Tree, error) { + if len(rpath) == 0 { + return t, nil + } + + paths := strings.Split(rpath, "/") + var ( + err error + g = t + p = t + te *TreeEntry + ) + for _, name := range paths { + te, err = p.GetTreeEntryByPath(name) + if err != nil { + return nil, err + } + + g, err = t.repo.getTree(te.ID) + if err != nil { + return nil, err + } + g.ptree = p + p = g + } + return g, nil +} + +// ListEntries returns all entries of current tree. +func (t *Tree) ListEntries() (Entries, error) { + if t.entriesParsed { + return t.entries, nil + } + + stdout, err := NewCommand("ls-tree", t.ID.String()).RunInDirBytes(t.repo.Path) + if err != nil { + return nil, err + } + t.entries, err = parseTreeEntries(stdout, t) + return t.entries, err +} diff --git a/vendor/code.gitea.io/git/tree_blob.go b/vendor/code.gitea.io/git/tree_blob.go new file mode 100644 index 0000000000000..b3d205d8e10e9 --- /dev/null +++ b/vendor/code.gitea.io/git/tree_blob.go @@ -0,0 +1,59 @@ +// 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 git + +import ( + "path" + "strings" +) + +// GetTreeEntryByPath get the tree entries accroding the sub dir +func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { + if len(relpath) == 0 { + return &TreeEntry{ + ID: t.ID, + Type: ObjectTree, + mode: EntryModeTree, + }, nil + } + + relpath = path.Clean(relpath) + parts := strings.Split(relpath, "/") + var err error + tree := t + for i, name := range parts { + if i == len(parts)-1 { + entries, err := tree.ListEntries() + if err != nil { + return nil, err + } + for _, v := range entries { + if v.name == name { + return v, nil + } + } + } else { + tree, err = tree.SubTree(name) + if err != nil { + return nil, err + } + } + } + return nil, ErrNotExist{"", relpath} +} + +// GetBlobByPath get the blob object accroding the path +func (t *Tree) GetBlobByPath(relpath string) (*Blob, error) { + entry, err := t.GetTreeEntryByPath(relpath) + if err != nil { + return nil, err + } + + if !entry.IsDir() { + return entry.Blob(), nil + } + + return nil, ErrNotExist{"", relpath} +} diff --git a/vendor/code.gitea.io/git/tree_entry.go b/vendor/code.gitea.io/git/tree_entry.go new file mode 100644 index 0000000000000..6201eef8fd5bd --- /dev/null +++ b/vendor/code.gitea.io/git/tree_entry.go @@ -0,0 +1,200 @@ +// 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 git + +import ( + "io" + "sort" + "strconv" + "strings" +) + +// EntryMode the type of the object in the git tree +type EntryMode int + +// There are only a few file modes in Git. They look like unix file modes, but they can only be +// one of these. +const ( + // EntryModeBlob + EntryModeBlob EntryMode = 0100644 + // EntryModeExec + EntryModeExec EntryMode = 0100755 + // EntryModeSymlink + EntryModeSymlink EntryMode = 0120000 + // EntryModeCommit + EntryModeCommit EntryMode = 0160000 + // EntryModeTree + EntryModeTree EntryMode = 0040000 +) + +// TreeEntry the leaf in the git tree +type TreeEntry struct { + ID SHA1 + Type ObjectType + + mode EntryMode + name string + + ptree *Tree + + commited bool + + size int64 + sized bool +} + +// Name returns the name of the entry +func (te *TreeEntry) Name() string { + return te.name +} + +// Size returns the size of the entry +func (te *TreeEntry) Size() int64 { + if te.IsDir() { + return 0 + } else if te.sized { + return te.size + } + + stdout, err := NewCommand("cat-file", "-s", te.ID.String()).RunInDir(te.ptree.repo.Path) + if err != nil { + return 0 + } + + te.sized = true + te.size, _ = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64) + return te.size +} + +// IsSubModule if the entry is a sub module +func (te *TreeEntry) IsSubModule() bool { + return te.mode == EntryModeCommit +} + +// IsDir if the entry is a sub dir +func (te *TreeEntry) IsDir() bool { + return te.mode == EntryModeTree +} + +// IsLink if the entry is a symlink +func (te *TreeEntry) IsLink() bool { + return te.mode == EntryModeSymlink +} + +// Blob retrun the blob object the entry +func (te *TreeEntry) Blob() *Blob { + return &Blob{ + repo: te.ptree.repo, + TreeEntry: te, + } +} + +// FollowLink returns the entry pointed to by a symlink +func (te *TreeEntry) FollowLink() (*TreeEntry, error) { + if !te.IsLink() { + return nil, ErrBadLink{te.Name(), "not a symlink"} + } + + // read the link + r, err := te.Blob().Data() + if err != nil { + return nil, err + } + buf := make([]byte, te.Size()) + _, err = io.ReadFull(r, buf) + if err != nil { + return nil, err + } + + lnk := string(buf) + t := te.ptree + + // traverse up directories + for ; t != nil && strings.HasPrefix(lnk, "../"); lnk = lnk[3:] { + t = t.ptree + } + + if t == nil { + return nil, ErrBadLink{te.Name(), "points outside of repo"} + } + + target, err := t.GetTreeEntryByPath(lnk) + if err != nil { + if IsErrNotExist(err) { + return nil, ErrBadLink{te.Name(), "broken link"} + } + return nil, err + } + return target, nil +} + +// GetSubJumpablePathName return the full path of subdirectory jumpable ( contains only one directory ) +func (te *TreeEntry) GetSubJumpablePathName() string { + if te.IsSubModule() || !te.IsDir() { + return "" + } + tree, err := te.ptree.SubTree(te.name) + if err != nil { + return te.name + } + entries, _ := tree.ListEntries() + if len(entries) == 1 && entries[0].IsDir() { + name := entries[0].GetSubJumpablePathName() + if name != "" { + return te.name + "/" + name + } + } + return te.name +} + +// Entries a list of entry +type Entries []*TreeEntry + +type customSortableEntries struct { + Comparer func(s1, s2 string) bool + Entries +} + +var sorter = []func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool{ + func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { + return (t1.IsDir() || t1.IsSubModule()) && !t2.IsDir() && !t2.IsSubModule() + }, + func(t1, t2 *TreeEntry, cmp func(s1, s2 string) bool) bool { + return cmp(t1.name, t2.name) + }, +} + +func (ctes customSortableEntries) Len() int { return len(ctes.Entries) } + +func (ctes customSortableEntries) Swap(i, j int) { + ctes.Entries[i], ctes.Entries[j] = ctes.Entries[j], ctes.Entries[i] +} + +func (ctes customSortableEntries) Less(i, j int) bool { + t1, t2 := ctes.Entries[i], ctes.Entries[j] + var k int + for k = 0; k < len(sorter)-1; k++ { + s := sorter[k] + switch { + case s(t1, t2, ctes.Comparer): + return true + case s(t2, t1, ctes.Comparer): + return false + } + } + return sorter[k](t1, t2, ctes.Comparer) +} + +// Sort sort the list of entry +func (tes Entries) Sort() { + sort.Sort(customSortableEntries{func(s1, s2 string) bool { + return s1 < s2 + }, tes}) +} + +// CustomSort customizable string comparing sort entry list +func (tes Entries) CustomSort(cmp func(s1, s2 string) bool) { + sort.Sort(customSortableEntries{cmp, tes}) +} diff --git a/vendor/code.gitea.io/git/utils.go b/vendor/code.gitea.io/git/utils.go new file mode 100644 index 0000000000000..8f010321cf836 --- /dev/null +++ b/vendor/code.gitea.io/git/utils.go @@ -0,0 +1,96 @@ +// 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 git + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" +) + +// ObjectCache provides thread-safe cache opeations. +type ObjectCache struct { + lock sync.RWMutex + cache map[string]interface{} +} + +func newObjectCache() *ObjectCache { + return &ObjectCache{ + cache: make(map[string]interface{}, 10), + } +} + +// Set add obj to cache +func (oc *ObjectCache) Set(id string, obj interface{}) { + oc.lock.Lock() + defer oc.lock.Unlock() + + oc.cache[id] = obj +} + +// Get get cached obj by id +func (oc *ObjectCache) Get(id string) (interface{}, bool) { + oc.lock.RLock() + defer oc.lock.RUnlock() + + obj, has := oc.cache[id] + return obj, has +} + +// isDir returns true if given path is a directory, +// or returns false when it's a file or does not exist. +func isDir(dir string) bool { + f, e := os.Stat(dir) + if e != nil { + return false + } + return f.IsDir() +} + +// isFile returns true if given path is a file, +// or returns false when it's a directory or does not exist. +func isFile(filePath string) bool { + f, e := os.Stat(filePath) + if e != nil { + return false + } + return !f.IsDir() +} + +// isExist checks whether a file or directory exists. +// It returns false when the file or directory does not exist. +func isExist(path string) bool { + _, err := os.Stat(path) + return err == nil || os.IsExist(err) +} + +func concatenateError(err error, stderr string) error { + if len(stderr) == 0 { + return err + } + return fmt.Errorf("%v - %s", err, stderr) +} + +// If the object is stored in its own file (i.e not in a pack file), +// this function returns the full path to the object file. +// It does not test if the file exists. +func filepathFromSHA1(rootdir, sha1 string) string { + return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:]) +} + +// RefEndName return the end name of a ref name +func RefEndName(refStr string) string { + if strings.HasPrefix(refStr, BranchPrefix) { + return refStr[len(BranchPrefix):] + } + + if strings.HasPrefix(refStr, TagPrefix) { + return refStr[len(TagPrefix):] + } + + return refStr +} diff --git a/vendor/code.gitea.io/sdk/LICENSE b/vendor/code.gitea.io/sdk/LICENSE new file mode 100644 index 0000000000000..10aeba46bcfc9 --- /dev/null +++ b/vendor/code.gitea.io/sdk/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 0000000000000..4071b6f187fcc --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/admin_org.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" +) + +// 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 0000000000000..cf565ffa38b1c --- /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/attachment.go b/vendor/code.gitea.io/sdk/gitea/attachment.go new file mode 100644 index 0000000000000..8c527de735c39 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/attachment.go @@ -0,0 +1,92 @@ +// 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 +// swagger:model +type Attachment struct { + ID int64 `json:"id"` + Name string `json:"name"` + Size int64 `json:"size"` + DownloadCount int64 `json:"download_count"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + UUID string `json:"uuid"` + DownloadURL string `json:"browser_download_url"` +} + +// ListReleaseAttachments list release's attachments +func (c *Client) ListReleaseAttachments(user, repo string, release int64) ([]*Attachment, error) { + attachments := make([]*Attachment, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases/%d/assets", user, repo, release), + 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 +} + +// 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 +} + +// EditAttachmentOptions options for editing attachments +// swagger:model +type EditAttachmentOptions struct { + Name string `json:"name"` +} 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 0000000000000..6bd327db4623c --- /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 0000000000000..57222498ef54c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/fork.go @@ -0,0 +1,39 @@ +// 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" +) + +// ListForks list a repository's forks +func (c *Client) ListForks(user, repo string) ([]*Repository, error) { + forks := make([]*Repository, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/forks", user, repo), + nil, nil, &forks) + return forks, err +} + +// 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) + err = c.getParsedResponse("POST", + fmt.Sprintf("/repos/%s/%s/forks", user, repo), + jsonHeader, bytes.NewReader(body), &fork) + return fork, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/gitea.go b/vendor/code.gitea.io/sdk/gitea/gitea.go new file mode 100644 index 0000000000000..374a3faa9604c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/gitea.go @@ -0,0 +1,104 @@ +// 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 ( + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + "strings" +) + +// Version return the library version +func Version() string { + return "0.12.3" +} + +// Client represents a Gogs API client. +type Client struct { + url string + accessToken string + client *http.Client +} + +// NewClient initializes and returns a API client. +func NewClient(url, token string) *Client { + return &Client{ + url: strings.TrimSuffix(url, "/"), + accessToken: token, + client: &http.Client{}, + } +} + +// SetHTTPClient replaces default http.Client with user given one. +func (c *Client) SetHTTPClient(client *http.Client) { + c.client = client +} + +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 + } + req.Header.Set("Authorization", "token "+c.accessToken) + 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 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 { + return nil, err + } + 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/hook.go b/vendor/code.gitea.io/sdk/gitea/hook.go new file mode 100644 index 0000000000000..f346381679848 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/hook.go @@ -0,0 +1,531 @@ +// 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" + "errors" + "fmt" + "strings" + "time" +) + +var ( + // ErrInvalidReceiveHook FIXME + ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") +) + +// 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"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` +} + +// HookList represents a list of API hook. +type HookList []*Hook + +// ListOrgHooks list all the hooks of one organization +func (c *Client) ListOrgHooks(org string) (HookList, error) { + hooks := make([]*Hook, 0, 10) + return hooks, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/hooks", org), nil, nil, &hooks) +} + +// ListRepoHooks list all the hooks of one repository +func (c *Client) ListRepoHooks(user, repo string) (HookList, error) { + hooks := make([]*Hook, 0, 10) + return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), 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 { + // required: true + // enum: gitea,gogs,slack,discord + Type string `json:"type" binding:"Required"` + // required: true + Config map[string]string `json:"config" binding:"Required"` + Events []string `json:"events"` + // default: false + 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"` + 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("/org/%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 +} + +// Payloader payload is some part of one hook +type Payloader interface { + SetSecret(string) + JSONPayload() ([]byte, error) +} + +// PayloadUser represents the author or committer of a commit +type PayloadUser struct { + // Full name of the commit author + Name string `json:"name"` + // swagger:strfmt email + 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"` + // swagger:strfmt date-time + Timestamp time.Time `json:"timestamp"` +} + +// 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"` +} + +var ( + _ Payloader = &CreatePayload{} + _ Payloader = &DeletePayload{} + _ Payloader = &ForkPayload{} + _ Payloader = &PushPayload{} + _ Payloader = &IssuePayload{} + _ Payloader = &IssueCommentPayload{} + _ Payloader = &PullRequestPayload{} + _ Payloader = &RepositoryPayload{} + _ Payloader = &ReleasePayload{} +) + +// _________ __ +// \_ ___ \_______ ____ _____ _/ |_ ____ +// / \ \/\_ __ \_/ __ \\__ \\ __\/ __ \ +// \ \____| | \/\ ___/ / __ \| | \ ___/ +// \______ /|__| \___ >____ /__| \___ > +// \/ \/ \/ \/ + +// CreatePayload FIXME +type CreatePayload struct { + Secret string `json:"secret"` + Sha string `json:"sha"` + Ref string `json:"ref"` + RefType string `json:"ref_type"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret FIXME +func (p *CreatePayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload return payload information +func (p *CreatePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ParseCreateHook parses create event hook content. +func ParseCreateHook(raw []byte) (*CreatePayload, error) { + hook := new(CreatePayload) + if err := json.Unmarshal(raw, hook); err != nil { + return nil, err + } + + // it is possible the JSON was parsed, however, + // was not from Gogs (maybe was from Bitbucket) + // So we'll check to be sure certain key fields + // were populated + switch { + case hook.Repo == nil: + return nil, ErrInvalidReceiveHook + case len(hook.Ref) == 0: + return nil, ErrInvalidReceiveHook + } + return hook, nil +} + +// ________ .__ __ +// \______ \ ____ | | _____/ |_ ____ +// | | \_/ __ \| | _/ __ \ __\/ __ \ +// | ` \ ___/| |_\ ___/| | \ ___/ +// /_______ /\___ >____/\___ >__| \___ > +// \/ \/ \/ \/ + +// PusherType define the type to push +type PusherType string + +// describe all the PusherTypes +const ( + PusherTypeUser PusherType = "user" +) + +// DeletePayload represents delete payload +type DeletePayload struct { + Ref string `json:"ref"` + RefType string `json:"ref_type"` + PusherType PusherType `json:"pusher_type"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *DeletePayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *DeletePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ___________ __ +// \_ _____/__________| | __ +// | __)/ _ \_ __ \ |/ / +// | \( <_> ) | \/ < +// \___ / \____/|__| |__|_ \ +// \/ \/ + +// ForkPayload represents fork payload +type ForkPayload struct { + Forkee *Repository `json:"forkee"` + Repo *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *ForkPayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *ForkPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// HookIssueCommentAction defines hook issue comment action +type HookIssueCommentAction string + +// all issue comment actions +const ( + HookIssueCommentCreated HookIssueCommentAction = "created" + HookIssueCommentEdited HookIssueCommentAction = "edited" + HookIssueCommentDeleted HookIssueCommentAction = "deleted" +) + +// IssueCommentPayload represents a payload information of issue comment event. +type IssueCommentPayload struct { + Action HookIssueCommentAction `json:"action"` + Issue *Issue `json:"issue"` + Comment *Comment `json:"comment"` + Changes *ChangesPayload `json:"changes,omitempty"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *IssueCommentPayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *IssueCommentPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// __________ .__ +// \______ \ ____ | | ____ _____ ______ ____ +// | _// __ \| | _/ __ \\__ \ / ___// __ \ +// | | \ ___/| |_\ ___/ / __ \_\___ \\ ___/ +// |____|_ /\___ >____/\___ >____ /____ >\___ > +// \/ \/ \/ \/ \/ \/ + +// HookReleaseAction defines hook release action type +type HookReleaseAction string + +// all release actions +const ( + HookReleasePublished HookReleaseAction = "published" + HookReleaseUpdated HookReleaseAction = "updated" + HookReleaseDeleted HookReleaseAction = "deleted" +) + +// ReleasePayload represents a payload information of release event. +type ReleasePayload struct { + Action HookReleaseAction `json:"action"` + Release *Release `json:"release"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret implements Payload +func (p *ReleasePayload) SetSecret(secret string) { +} + +// JSONPayload implements Payload +func (p *ReleasePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// __________ .__ +// \______ \__ __ _____| |__ +// | ___/ | \/ ___/ | \ +// | | | | /\___ \| Y \ +// |____| |____//____ >___| / +// \/ \/ + +// PushPayload represents a payload information of push event. +type PushPayload struct { + Secret string `json:"secret"` + Ref string `json:"ref"` + Before string `json:"before"` + After string `json:"after"` + CompareURL string `json:"compare_url"` + Commits []*PayloadCommit `json:"commits"` + Repo *Repository `json:"repository"` + Pusher *User `json:"pusher"` + Sender *User `json:"sender"` +} + +// SetSecret FIXME +func (p *PushPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload FIXME +func (p *PushPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ParsePushHook parses push event hook content. +func ParsePushHook(raw []byte) (*PushPayload, error) { + hook := new(PushPayload) + if err := json.Unmarshal(raw, hook); err != nil { + return nil, err + } + + switch { + case hook.Repo == nil: + return nil, ErrInvalidReceiveHook + case len(hook.Ref) == 0: + return nil, ErrInvalidReceiveHook + } + return hook, nil +} + +// Branch returns branch name from a payload +func (p *PushPayload) Branch() string { + return strings.Replace(p.Ref, "refs/heads/", "", -1) +} + +// .___ +// | | ______ ________ __ ____ +// | |/ ___// ___/ | \_/ __ \ +// | |\___ \ \___ \| | /\ ___/ +// |___/____ >____ >____/ \___ > +// \/ \/ \/ + +// HookIssueAction FIXME +type HookIssueAction string + +const ( + // HookIssueOpened opened + HookIssueOpened HookIssueAction = "opened" + // HookIssueClosed closed + HookIssueClosed HookIssueAction = "closed" + // HookIssueReOpened reopened + HookIssueReOpened HookIssueAction = "reopened" + // HookIssueEdited edited + HookIssueEdited HookIssueAction = "edited" + // HookIssueAssigned assigned + HookIssueAssigned HookIssueAction = "assigned" + // HookIssueUnassigned unassigned + HookIssueUnassigned HookIssueAction = "unassigned" + // HookIssueLabelUpdated label_updated + HookIssueLabelUpdated HookIssueAction = "label_updated" + // HookIssueLabelCleared label_cleared + HookIssueLabelCleared HookIssueAction = "label_cleared" + // HookIssueSynchronized synchronized + HookIssueSynchronized HookIssueAction = "synchronized" + // HookIssueMilestoned is an issue action for when a milestone is set on an issue. + HookIssueMilestoned HookIssueAction = "milestoned" + // HookIssueDemilestoned is an issue action for when a milestone is cleared on an issue. + HookIssueDemilestoned HookIssueAction = "demilestoned" +) + +// IssuePayload represents the payload information that is sent along with an issue event. +type IssuePayload struct { + Secret string `json:"secret"` + Action HookIssueAction `json:"action"` + Index int64 `json:"number"` + Changes *ChangesPayload `json:"changes,omitempty"` + Issue *Issue `json:"issue"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret modifies the secret of the IssuePayload. +func (p *IssuePayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload encodes the IssuePayload to JSON, with an indentation of two spaces. +func (p *IssuePayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +// ChangesFromPayload FIXME +type ChangesFromPayload struct { + From string `json:"from"` +} + +// ChangesPayload FIXME +type ChangesPayload struct { + Title *ChangesFromPayload `json:"title,omitempty"` + Body *ChangesFromPayload `json:"body,omitempty"` +} + +// __________ .__ .__ __________ __ +// \______ \__ __| | | | \______ \ ____ ________ __ ____ _______/ |_ +// | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\ +// | | | | / |_| |__ | | \ ___< <_| | | /\ ___/ \___ \ | | +// |____| |____/|____/____/ |____|_ /\___ >__ |____/ \___ >____ > |__| +// \/ \/ |__| \/ \/ + +// PullRequestPayload represents a payload information of pull request event. +type PullRequestPayload struct { + Secret string `json:"secret"` + Action HookIssueAction `json:"action"` + Index int64 `json:"number"` + Changes *ChangesPayload `json:"changes,omitempty"` + PullRequest *PullRequest `json:"pull_request"` + Repository *Repository `json:"repository"` + Sender *User `json:"sender"` +} + +// SetSecret modifies the secret of the PullRequestPayload. +func (p *PullRequestPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload FIXME +func (p *PullRequestPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} + +//__________ .__ __ +//\______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. +// | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | +// | | \ ___/| |_> > <_> )___ \| || | ( <_> ) | \/\___ | +// |____|_ /\___ > __/ \____/____ >__||__| \____/|__| / ____| +// \/ \/|__| \/ \/ + +// HookRepoAction an action that happens to a repo +type HookRepoAction string + +const ( + // HookRepoCreated created + HookRepoCreated HookRepoAction = "created" + // HookRepoDeleted deleted + HookRepoDeleted HookRepoAction = "deleted" +) + +// RepositoryPayload payload for repository webhooks +type RepositoryPayload struct { + Secret string `json:"secret"` + Action HookRepoAction `json:"action"` + Repository *Repository `json:"repository"` + Organization *User `json:"organization"` + Sender *User `json:"sender"` +} + +// SetSecret set the payload's secret +func (p *RepositoryPayload) SetSecret(secret string) { + p.Secret = secret +} + +// JSONPayload JSON representation of the payload +func (p *RepositoryPayload) JSONPayload() ([]byte, error) { + return json.MarshalIndent(p, "", " ") +} 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 0000000000000..2c8127c609734 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_comment.go @@ -0,0 +1,76 @@ +// 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" + "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"` + Body string `json:"body"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` +} + +// ListIssueComments list comments on an issue. +func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, error) { + comments := make([]*Comment, 0, 10) + return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments) +} + +// ListRepoIssueComments list comments for a given repo. +func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) { + comments := make([]*Comment, 0, 10) + return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments) +} + +// CreateIssueCommentOption options for creating a comment on an issue +type CreateIssueCommentOption struct { + // required:true + Body string `json:"body" binding:"Required"` +} + +// 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 { + // required: true + Body string `json:"body" binding:"Required"` +} + +// EditIssueComment edits an issue comment. +func (c *Client) EditIssueComment(owner, repo string, index, 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/%d/comments/%d", owner, repo, index, commentID), jsonHeader, bytes.NewReader(body), comment) +} + +// DeleteIssueComment deletes an issue comment. +func (c *Client) DeleteIssueComment(owner, repo string, index, commentID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, 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 0000000000000..47d1b8221e98b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_label.go @@ -0,0 +1,122 @@ +// 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 +// swagger:model +type Label struct { + ID int64 `json:"id"` + Name string `json:"name"` + // example: 00aabb + Color string `json:"color"` + URL string `json:"url"` +} + +// ListRepoLabels list labels of one repository +func (c *Client) ListRepoLabels(owner, repo string) ([]*Label, error) { + labels := make([]*Label, 0, 10) + return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/labels", owner, repo), nil, nil, &labels) +} + +// 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 { + // required:true + Name string `json:"name" binding:"Required"` + // required:true + // example: #00aabb + Color string `json:"color" binding:"Required;Size(7)"` +} + +// CreateLabel create one label of repository +func (c *Client) CreateLabel(owner, repo string, opt CreateLabelOption) (*Label, error) { + 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"` +} + +// 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 +} + +// IssueLabelsOption a collection of labels +type IssueLabelsOption struct { + // list of label IDs + Labels []int64 `json:"labels"` +} + +// GetIssueLabels get labels of one issue via issue id +func (c *Client) GetIssueLabels(owner, repo string, index int64) ([]*Label, error) { + labels := make([]*Label, 0, 5) + return labels, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/labels", owner, repo, index), nil, nil, &labels) +} + +// 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 0000000000000..775a6a9117510 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_milestone.go @@ -0,0 +1,80 @@ +// 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" + "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"` + // swagger:strfmt date-time + Closed *time.Time `json:"closed_at"` + // swagger:strfmt date-time + Deadline *time.Time `json:"due_on"` +} + +// ListRepoMilestones list all the milestones of one repository +func (c *Client) ListRepoMilestones(owner, repo string) ([]*Milestone, error) { + milestones := make([]*Milestone, 0, 10) + return milestones, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), nil, nil, &milestones) +} + +// 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"` + // swagger:strfmt date-time + 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) + return milestone, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/milestones", owner, repo), jsonHeader, bytes.NewReader(body), milestone) +} + +// 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_tracked_time.go b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go new file mode 100644 index 0000000000000..7f4b64cbb3f99 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/issue_tracked_time.go @@ -0,0 +1,68 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created"` + // Time in seconds + Time int64 `json:"time"` + UserID int64 `json:"user_id"` + IssueID int64 `json:"issue_id"` +} + +// TrackedTimes represent a list of tracked times +type TrackedTimes []*TrackedTime + +// GetUserTrackedTimes list tracked times of a user +func (c *Client) GetUserTrackedTimes(owner, repo, user string) (TrackedTimes, error) { + times := make(TrackedTimes, 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) (TrackedTimes, error) { + times := make(TrackedTimes, 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() (TrackedTimes, error) { + times := make(TrackedTimes, 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 + // required: true + Time int64 `json:"time" binding:"Required"` +} + +// 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) +} + +// ListTrackedTimes get tracked times of one issue via issue id +func (c *Client) ListTrackedTimes(owner, repo string, index int64) (TrackedTimes, error) { + times := make(TrackedTimes, 0, 5) + return times, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/times", owner, repo, index), nil, nil, ×) +} diff --git a/vendor/code.gitea.io/sdk/gitea/lfs_lock.go b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go new file mode 100644 index 0000000000000..356636a3a2519 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/lfs_lock.go @@ -0,0 +1,65 @@ +// 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 ( + "time" +) + +// LFSLock represent a lock +// for use with the locks API. +type LFSLock struct { + ID string `json:"id"` + Path string `json:"path"` + LockedAt time.Time `json:"locked_at"` + Owner *LFSLockOwner `json:"owner"` +} + +// LFSLockOwner represent a lock owner +// for use with the locks API. +type LFSLockOwner struct { + Name string `json:"name"` +} + +// LFSLockRequest contains the path of the lock to create +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock +type LFSLockRequest struct { + Path string `json:"path"` +} + +// LFSLockResponse represent a lock created +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#create-lock +type LFSLockResponse struct { + Lock *LFSLock `json:"lock"` +} + +// LFSLockList represent a list of lock requested +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks +type LFSLockList struct { + Locks []*LFSLock `json:"locks"` + Next string `json:"next_cursor,omitempty"` +} + +// LFSLockListVerify represent a list of lock verification requested +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#list-locks-for-verification +type LFSLockListVerify struct { + Ours []*LFSLock `json:"ours"` + Theirs []*LFSLock `json:"theirs"` + Next string `json:"next_cursor,omitempty"` +} + +// LFSLockError contains information on the error that occurs +type LFSLockError struct { + Message string `json:"message"` + Lock *LFSLock `json:"lock,omitempty"` + Documentation string `json:"documentation_url,omitempty"` + RequestID string `json:"request_id,omitempty"` +} + +// LFSLockDeleteRequest contains params of a delete request +// https://github.com/git-lfs/git-lfs/blob/master/docs/api/locking.md#delete-lock +type LFSLockDeleteRequest struct { + Force bool `json:"force"` +} diff --git a/vendor/code.gitea.io/sdk/gitea/miscellaneous.go b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go new file mode 100644 index 0000000000000..3735047b7f886 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/miscellaneous.go @@ -0,0 +1,52 @@ +// 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 + +// SearchResults results of a successful search +type SearchResults struct { + OK bool `json:"ok"` + Data []*Repository `json:"data"` +} + +// SearchError error of a failed search +type SearchError struct { + OK bool `json:"ok"` + Error string `json:"error"` +} + +// MarkdownOption markdown options +type MarkdownOption struct { + // Text markdown to render + // + // in: body + Text string + // Mode to render + // + // in: body + Mode string + // Context to render + // + // in: body + Context string + // Is it a wiki page ? + // + // in: body + Wiki bool +} + +// MarkdownRender is a rendered markdown document +// swagger:response MarkdownRender +type MarkdownRender string + +// ServerVersion wraps the version of the server +type ServerVersion struct { + Version string `json:"version"` +} + +// ServerVersion returns the version of the server +func (c *Client) ServerVersion() (string, error) { + v := ServerVersion{} + return v.Version, c.getParsedResponse("GET", "/api/v1/version", nil, nil, &v) +} 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 0000000000000..19238d1028453 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org.go @@ -0,0 +1,68 @@ +// 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" +) + +// 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"` +} + +// ListMyOrgs list all of current user's organizations +func (c *Client) ListMyOrgs() ([]*Organization, error) { + orgs := make([]*Organization, 0, 5) + return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs) +} + +// ListUserOrgs list all of some user's organizations +func (c *Client) ListUserOrgs(user string) ([]*Organization, error) { + orgs := make([]*Organization, 0, 5) + return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs) +} + +// 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 { + // required: true + UserName string `json:"username" binding:"Required"` + FullName string `json:"full_name"` + Description string `json:"description"` + Website string `json:"website"` + Location string `json:"location"` +} + +// 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"` +} + +// 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 +} 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 0000000000000..9bb95af3e2624 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_member.go @@ -0,0 +1,26 @@ +// 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" +) + +// AddOrgMembershipOption add user to organization options +type AddOrgMembershipOption struct { + Role string `json:"role" binding:"Required"` +} + +// AddOrgMembership add some one to an organization's member +func (c *Client) AddOrgMembership(org, user string, opt AddOrgMembershipOption) error { + body, err := json.Marshal(&opt) + if err != nil { + return err + } + _, err = c.getResponse("PUT", fmt.Sprintf("/orgs/%s/membership/%s", org, user), jsonHeader, bytes.NewReader(body)) + return err +} 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 0000000000000..2fc6796d43ff9 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/org_team.go @@ -0,0 +1,32 @@ +// 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 + +// Team represents a team in an organization +type Team struct { + ID int64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + // enum: none,read,write,admin,owner + Permission string `json:"permission"` +} + +// CreateTeamOption options for creating a team +type CreateTeamOption struct { + // required: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` + Description string `json:"description" binding:"MaxSize(255)"` + // enum: read,write,admin + Permission string `json:"permission"` +} + +// EditTeamOption options for editing a team +type EditTeamOption struct { + // required: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"` + Description string `json:"description" binding:"MaxSize(255)"` + // enum: read,write,admin + Permission string `json:"permission"` +} 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 0000000000000..6fcdd1d41b7e4 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/pull.go @@ -0,0 +1,151 @@ +// 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" + "time" +) + +// 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"` + // swagger:strfmt date-time + 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"` + + // swagger:strfmt date-time + Deadline *time.Time `json:"due_date"` + + // swagger:strfmt date-time + Created *time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated *time.Time `json:"updated_at"` + // swagger:strfmt date-time + Closed *time.Time `json:"closed_at"` +} + +// 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"` +} + +// ListPullRequestsOptions options for listing pull requests +type ListPullRequestsOptions struct { + Page int `json:"page"` + State string `json:"state"` +} + +// ListRepoPullRequests list PRs of one repository +func (c *Client) ListRepoPullRequests(owner, repo string, opt ListPullRequestsOptions) ([]*PullRequest, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + prs := make([]*PullRequest, 0, 10) + return prs, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/pulls", owner, repo), jsonHeader, bytes.NewReader(body), &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" binding:"Required"` + Base string `json:"base" binding:"Required"` + Title string `json:"title" binding:"Required"` + Body string `json:"body"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + // swagger:strfmt date-time + 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"` + Assignee string `json:"assignee"` + Assignees []string `json:"assignees"` + Milestone int64 `json:"milestone"` + Labels []int64 `json:"labels"` + State *string `json:"state"` + // swagger:strfmt date-time + 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/issues/%d", owner, repo, index), + jsonHeader, bytes.NewReader(body), pr) +} + +// MergePullRequest merge a PR to repository by PR id +func (c *Client) MergePullRequest(owner, repo string, index int64) error { + _, err := c.getResponse("POST", fmt.Sprintf("/repos/%s/%s/pulls/%d/merge", owner, repo, index), nil, nil) + return err +} + +// 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/release.go b/vendor/code.gitea.io/sdk/gitea/release.go new file mode 100644 index 0000000000000..396251dcac9d8 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/release.go @@ -0,0 +1,105 @@ +// 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"` + // swagger:strfmt date-time + CreatedAt time.Time `json:"created_at"` + // swagger:strfmt date-time + PublishedAt time.Time `json:"published_at"` + Publisher *User `json:"author"` + Attachments []*Attachment `json:"assets"` +} + +// ListReleases list releases of a repository +func (c *Client) ListReleases(user, repo string) ([]*Release, error) { + releases := make([]*Release, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/releases", user, repo), + 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 { + // required: true + TagName string `json:"tag_name" binding:"Required"` + 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 0000000000000..339cbd33deaac --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo.go @@ -0,0 +1,155 @@ +// 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" + "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"` + 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + Permissions *Permission `json:"permissions,omitempty"` +} + +// ListMyRepos lists all repositories for the authenticated user that has access to. +func (c *Client) ListMyRepos() ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos) +} + +// ListUserRepos list all repositories of one user by user's name +func (c *Client) ListUserRepos(user string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/repos", user), nil, nil, &repos) +} + +// ListOrgRepos list all repositories of one organization by organization's name +func (c *Client) ListOrgRepos(org string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s/repos", org), nil, nil, &repos) +} + +// CreateRepoOption options when creating repository +// swagger:model +type CreateRepoOption struct { + // Name of the repository to create + // + // required: true + // unique: true + Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(100)"` + // Description of the repository to create + Description string `json:"description" binding:"MaxSize(255)"` + // Whether the repository is private + Private bool `json:"private"` + // 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"` +} + +// 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) +} + +// 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 { + // required: true + CloneAddr string `json:"clone_addr" binding:"Required"` + AuthUsername string `json:"auth_username"` + AuthPassword string `json:"auth_password"` + // required: true + UID int `json:"uid" binding:"Required"` + // required: true + RepoName string `json:"repo_name" binding:"Required"` + 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 0000000000000..481fc3386ee76 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_branch.go @@ -0,0 +1,27 @@ +// 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 ( + "fmt" +) + +// Branch represents a repository branch +type Branch struct { + Name string `json:"name"` + Commit *PayloadCommit `json:"commit"` +} + +// ListRepoBranches list all the branches of one repository +func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) { + branches := make([]*Branch, 0, 10) + return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches) +} + +// GetRepoBranch get one branch's information of one repository +func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) { + b := new(Branch) + return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b) +} 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 0000000000000..bd61a22cec4f5 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_collaborator.go @@ -0,0 +1,57 @@ +// 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" +) + +// ListCollaborators list a repository's collaborators +func (c *Client) ListCollaborators(user, repo string) ([]*User, error) { + collaborators := make([]*User, 0, 10) + err := c.getParsedResponse("GET", + fmt.Sprintf("/repos/%s/%s/collaborators", user, repo), + nil, nil, &collaborators) + return collaborators, err +} + +// IsCollaborator check if a user is a collaborator of a repository +func (c *Client) IsCollaborator(user, repo, collaborator string) (bool, error) { + status, err := c.getStatusCode("GET", + fmt.Sprintf("/repos/%s/%s/collaborators/%s", user, repo, collaborator), + nil, nil) + 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), nil, 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_file.go b/vendor/code.gitea.io/sdk/gitea/repo_file.go new file mode 100644 index 0000000000000..e6c89f0c0f28b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_file.go @@ -0,0 +1,15 @@ +// 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" +) + +// 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) +} 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 0000000000000..ec53311bdaa55 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_key.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 ( + "bytes" + "encoding/json" + "fmt" + "time" +) + +// DeployKey a deploy key +type DeployKey struct { + ID int64 `json:"id"` + Key string `json:"key"` + URL string `json:"url"` + Title string `json:"title"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + ReadOnly bool `json:"read_only"` +} + +// ListDeployKeys list all the deploy keys of one repository +func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) { + keys := make([]*DeployKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys) +} + +// 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) +} + +// CreateKeyOption options when creating a key +type CreateKeyOption struct { + // Title of the key to add + // + // required: true + // unique: true + Title string `json:"title" binding:"Required"` + // An armored SSH key to add + // + // required: true + // unique: true + Key string `json:"key" binding:"Required"` + // Describe if the key has only read access or read/write + // + // required: false + ReadOnly bool `json:"read_only"` +} + +// 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_watch.go b/vendor/code.gitea.io/sdk/gitea/repo_watch.go new file mode 100644 index 0000000000000..1005f9fbd84ea --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/repo_watch.go @@ -0,0 +1,41 @@ +// 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, pass string) ([]*Repository, error) { + repos := make([]*Repository, 0, 10) + return repos, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/subscriptions", user), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &repos) +} + +// WatchRepo start to watch a repository +func (c *Client) WatchRepo(user, pass, repoUser, repoName string) (*WatchInfo, error) { + i := new(WatchInfo) + return i, c.getParsedResponse("PUT", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, i) +} + +// UnWatchRepo start to watch a repository +func (c *Client) UnWatchRepo(user, pass, repoUser, repoName string) (int, error) { + return c.getStatusCode("DELETE", fmt.Sprintf("/repos/%s/%s/subscription", repoUser, repoName), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil) +} 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 0000000000000..3060ab1b2b23b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/status.go @@ -0,0 +1,97 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` +} + +// 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"` +} + +// 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"` +} + +// ListStatusesOption holds pagination information +type ListStatusesOption struct { + Page int +} + +// CreateStatus creates a new Status for a given Commit +// +// POST /repos/:owner/:repo/statuses/:sha +func (c *Client) CreateStatus(owner, repo, sha string, opts CreateStatusOption) (*Status, error) { + body, err := json.Marshal(&opts) + if err != nil { + return nil, err + } + status := &Status{} + return status, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/statuses/%s", owner, repo, sha), + jsonHeader, bytes.NewReader(body), status) +} + +// ListStatuses returns all statuses for a given Commit +// +// GET /repos/:owner/:repo/commits/:ref/statuses +func (c *Client) ListStatuses(owner, repo, sha string, opts ListStatusesOption) ([]*Status, error) { + statuses := make([]*Status, 0, 10) + return statuses, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/commits/%s/statuses?page=%d", owner, repo, sha, opts.Page), nil, nil, &statuses) +} + +// GetCombinedStatus returns the CombinedStatus for a given Commit +// +// GET /repos/:owner/:repo/commits/:ref/status +func (c *Client) GetCombinedStatus(owner, repo, sha string) (*CombinedStatus, error) { + status := &CombinedStatus{} + 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 0000000000000..57cf752316660 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user.go @@ -0,0 +1,51 @@ +// 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 ( + "encoding/json" + "fmt" +) + +// User represents a user +// swagger:model +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"` + // swagger:strfmt email + Email string `json:"email"` + // URL to the user's avatar + AvatarURL string `json:"avatar_url"` + // User locale + Language string `json:"language"` +} + +// MarshalJSON implements the json.Marshaler interface for User, adding field(s) for backward compatibility +func (u User) MarshalJSON() ([]byte, error) { + // Re-declaring User to avoid recursion + type shadow User + return json.Marshal(struct { + shadow + CompatUserName string `json:"username"` + }{shadow(u), u.UserName}) +} + +// 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 0000000000000..d3bfce971bad4 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_app.go @@ -0,0 +1,63 @@ +// 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/base64" + "encoding/json" + "fmt" + "net/http" +) + +// BasicAuthEncode generate base64 of basic auth head +func BasicAuthEncode(user, pass string) string { + return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass)) +} + +// AccessToken represents a API access token. +// swagger:response AccessToken +type AccessToken struct { + ID int64 `json:"id"` + Name string `json:"name"` + Sha1 string `json:"sha1"` +} + +// AccessTokenList represents a list of API access token. +// swagger:response AccessTokenList +type AccessTokenList []*AccessToken + +// ListAccessTokens lista all the access tokens of user +func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) { + tokens := make([]*AccessToken, 0, 10) + return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user), + http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens) +} + +// CreateAccessTokenOption options when create access token +// swagger:parameters userCreateToken +type CreateAccessTokenOption struct { + Name string `json:"name" binding:"Required"` +} + +// CreateAccessToken create one access token with options +func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) { + body, err := json.Marshal(&opt) + if err != nil { + return nil, err + } + t := new(AccessToken) + return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user), + http.Header{ + "content-type": []string{"application/json"}, + "Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, + bytes.NewReader(body), t) +} + +// DeleteAccessToken delete token with key id +func (c *Client) DeleteAccessToken(user string, keyID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/user/%s/tokens/%d", user, keyID), nil, 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 0000000000000..721f52144ba11 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_email.go @@ -0,0 +1,56 @@ +// 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" +) + +// Email an email address belonging to a user +type Email struct { + // swagger:strfmt email + Email string `json:"email"` + Verified bool `json:"verified"` + Primary bool `json:"primary"` +} + +// ListEmails all the email addresses of user +func (c *Client) ListEmails() ([]*Email, error) { + emails := make([]*Email, 0, 3) + return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails) +} + +// 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 0000000000000..a197a7f188220 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_follow.go @@ -0,0 +1,55 @@ +// 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" + +// ListMyFollowers list all the followers of current user +func (c *Client) ListMyFollowers(page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users) +} + +// ListFollowers list all the followers of one user +func (c *Client) ListFollowers(user string, page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users) +} + +// ListMyFollowing list all the users current user followed +func (c *Client) ListMyFollowing(page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users) +} + +// ListFollowing list all the users the user followed +func (c *Client) ListFollowing(user string, page int) ([]*User, error) { + users := make([]*User, 0, 10) + return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users) +} + +// 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 0000000000000..0817d89461a1c --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_gpgkey.go @@ -0,0 +1,80 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at,omitempty"` + // swagger:strfmt date-time + Expires time.Time `json:"expires_at,omitempty"` +} + +// GPGKeyEmail an email attached to a GPGKey +// swagger:model GPGKeyEmail +type GPGKeyEmail struct { + Email string `json:"email"` + Verified bool `json:"verified"` +} + +// CreateGPGKeyOption options create user GPG key +type CreateGPGKeyOption struct { + // An armored GPG key to add + // + // required: true + // unique: true + ArmoredKey string `json:"armored_public_key" binding:"Required"` +} + +// ListGPGKeys list all the GPG keys of the user +func (c *Client) ListGPGKeys(user string) ([]*GPGKey, error) { + keys := make([]*GPGKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/gpg_keys", user), nil, nil, &keys) +} + +// ListMyGPGKeys list all the GPG keys of current user +func (c *Client) ListMyGPGKeys() ([]*GPGKey, error) { + keys := make([]*GPGKey, 0, 10) + return keys, c.getParsedResponse("GET", "/user/gpg_keys", nil, nil, &keys) +} + +// 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) +} + +// 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 0000000000000..4488c033f1a37 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_key.go @@ -0,0 +1,57 @@ +// 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"` + // swagger:strfmt date-time + Created time.Time `json:"created_at,omitempty"` +} + +// ListPublicKeys list all the public keys of the user +func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) { + keys := make([]*PublicKey, 0, 10) + return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys) +} + +// ListMyPublicKeys list all the public keys of current user +func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) { + keys := make([]*PublicKey, 0, 10) + return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys) +} + +// 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) +} + +// 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 0000000000000..65ab980d66f86 --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/user_search.go @@ -0,0 +1,14 @@ +package gitea + +import "fmt" + +type searchUsersResponse struct { + Users []*User `json:"data"` +} + +// SearchUsers finds users by query +func (c *Client) SearchUsers(query string, limit int) ([]*User, error) { + resp := new(searchUsersResponse) + err := c.getParsedResponse("GET", fmt.Sprintf("/users/search?q=%s&limit=%d", query, limit), nil, nil, &resp) + return resp.Users, err +} diff --git a/vendor/code.gitea.io/sdk/gitea/utils.go b/vendor/code.gitea.io/sdk/gitea/utils.go new file mode 100644 index 0000000000000..80892a1e7a90b --- /dev/null +++ b/vendor/code.gitea.io/sdk/gitea/utils.go @@ -0,0 +1,26 @@ +// 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 ( + "net/http" +) + +var jsonHeader = http.Header{"content-type": []string{"application/json"}} + +// Bool return address of bool value +func Bool(v bool) *bool { + return &v +} + +// String return address of string value +func String(v string) *string { + return &v +} + +// Int64 return address of int64 value +func Int64(v int64) *int64 { + return &v +} From 6613309cfdbd1c19b638dc88df0414f8ee32aa5f Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Mon, 3 Sep 2018 12:58:32 +0800 Subject: [PATCH 15/21] update UI in issue pin --- templates/repo/issue/list.tmpl | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/templates/repo/issue/list.tmpl b/templates/repo/issue/list.tmpl index 68e91636290bb..39a30619a6e90 100644 --- a/templates/repo/issue/list.tmpl +++ b/templates/repo/issue/list.tmpl @@ -185,8 +185,14 @@
    + + {{if eq .Priority 0}} + + {{else}} + + {{end}} {{end}} -
    #{{.Index}}
    +
    #{{.Index}}
    {{.Title}} {{if .Ref}} @@ -196,14 +202,6 @@ {{.Name}} {{end}} - {{if $.IsWriter}} - {{if eq .Priority 0}} -
    pin
    - {{else}} -
    unpin
    - {{end}} - {{end}} - {{if .NumComments}} {{.NumComments}} {{end}} From 552ea894aff6ba5e9aad583dd9b079104282a3f3 Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Tue, 4 Sep 2018 17:33:57 +0800 Subject: [PATCH 16/21] renamed files --- models/{issus_priority.go => issuse_priority.go} | 2 +- models/{issus_priority_test.go => issuse_priority_test.go} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename models/{issus_priority.go => issuse_priority.go} (96%) rename models/{issus_priority_test.go => issuse_priority_test.go} (100%) diff --git a/models/issus_priority.go b/models/issuse_priority.go similarity index 96% rename from models/issus_priority.go rename to models/issuse_priority.go index 31c672e5bb224..f4d677bd5ebe3 100644 --- a/models/issus_priority.go +++ b/models/issuse_priority.go @@ -13,7 +13,7 @@ const ( PriorityDefault = 0 ) -// UpdateIssuePriority update priority for a specific issue +// UpdateIssuePriority updates the priority func UpdateIssuePriority(issue *Issue) error { if err := issue.loadRepo(x); err != nil { return err diff --git a/models/issus_priority_test.go b/models/issuse_priority_test.go similarity index 100% rename from models/issus_priority_test.go rename to models/issuse_priority_test.go From 5953bede7332b431238524564d47f636e694c50b Mon Sep 17 00:00:00 2001 From: zhanghelong Date: Fri, 14 Sep 2018 16:44:20 +0800 Subject: [PATCH 17/21] resolve conflicts --- Gopkg.lock | 332 +++-------------------------------------------------- 1 file changed, 19 insertions(+), 313 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 7126f73642b2c..8637a6b612fd9 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,86 +3,65 @@ [[projects]] branch = "master" - digest = "1:835585f8450b4ec12252d032b0f13e6571ecf846e49076f69067f2503a7c1e07" name = "code.gitea.io/git" packages = ["."] - pruneopts = "NUT" revision = "6ef79e80b3b06ca13a1f3a7b940903ebc73b44cb" [[projects]] branch = "master" - digest = "1:5e7f14543006a44047fb1d0df16da08b2ebc2428f1fd53bd8af26a2b34928b11" name = "code.gitea.io/sdk" packages = ["gitea"] - pruneopts = "NUT" revision = "021567c9c12fe289b8980c34e81e6684434dd082" [[projects]] - digest = "1:3fcef06a1a6561955c94af6c7757a6fa37605eb653f0d06ab960e5bb80092195" name = "github.com/PuerkitoBio/goquery" packages = ["."] - pruneopts = "NUT" revision = "ed7d758e9a34ba1f55e8084e0d731448b46921a8" [[projects]] - digest = "1:44121ca443aec4512ceaeec5047d0162b86bfcc26f35eadddda93bc265cb2e39" name = "github.com/RoaringBitmap/roaring" packages = ["."] - pruneopts = "NUT" revision = "1a28a7fa985680f9f4e1644c0a857ec359a444b0" version = "v0.4.7" [[projects]] branch = "master" - digest = "1:93367b6d47a8ccc7d14f9f493ccf103ccf5afb698559ff8e8f1999427ce27ace" name = "github.com/Smerity/govarint" packages = ["."] - pruneopts = "NUT" revision = "7265e41f48f15fd61751e16da866af3c704bb3ab" [[projects]] branch = "master" - digest = "1:d290f4b25abbf574f80f60c8a5603ddada784f13f436b91a9a927bc7ce5a0146" name = "github.com/Unknwon/cae" packages = [ ".", - "zip", + "zip" ] - pruneopts = "NUT" revision = "c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c" [[projects]] branch = "master" - digest = "1:7d23e6e1889b8bb4bbb37a564708fdab4497ce232c3a99d66406c975b642a6ff" name = "github.com/Unknwon/com" packages = ["."] - pruneopts = "NUT" revision = "7677a1d7c1137cd3dd5ba7a076d0c898a1ef4520" [[projects]] branch = "master" - digest = "1:a89bad9aea65873d45195417902ba1e6245114bdf1005d855909a7725b0361d1" name = "github.com/Unknwon/i18n" packages = ["."] - pruneopts = "NUT" revision = "b64d336589669d317928070e70ba0ae558f16633" [[projects]] - digest = "1:d311c4c0cfd13f237665b248a55c909d5b40815c06f28992f35cba3266ef27da" name = "github.com/Unknwon/paginater" packages = ["."] - pruneopts = "NUT" revision = "7748a72e01415173a27d79866b984328e7b0c12b" [[projects]] - digest = "1:fc86904a62ac4bfff8cfbe94f42231ce3d8cea8fe2506d5293eaef468f8eaecf" name = "github.com/andybalholm/cascadia" packages = ["."] - pruneopts = "NUT" revision = "349dd0209470eabd9514242c688c403c0926d266" [[projects]] - digest = "1:67351095005f164e748a5a21899d1403b03878cb2d40a7b0f742376e6eeda974" name = "github.com/blevesearch/bleve" packages = [ ".", @@ -124,353 +103,265 @@ "search/highlight/highlighter/simple", "search/query", "search/scorer", - "search/searcher", + "search/searcher" ] - pruneopts = "NUT" revision = "ff210fbc6d348ad67aa5754eaea11a463fcddafd" [[projects]] branch = "master" - digest = "1:b165e3f145596f4ff864a34e38e0b63c8e57bbaec2d5a234f234f7554b84c42b" name = "github.com/blevesearch/go-porterstemmer" packages = ["."] - pruneopts = "NUT" revision = "23a2c8e5cf1f380f27722c6d2ae8896431dc7d0e" [[projects]] - digest = "1:a64956a7766e0d081ebff30d8528db107118485d2ee89cab751e6506f5ab55ea" name = "github.com/blevesearch/segment" packages = ["."] - pruneopts = "NUT" revision = "db70c57796cc8c310613541dfade3dce627d09c7" [[projects]] - digest = "1:c7e0968c05659f3973148cd5c5387d6ee960a6ae1b2eaaec0b1d435d806458bb" name = "github.com/boltdb/bolt" packages = ["."] - pruneopts = "NUT" revision = "ccd680d8c1a0179ac3d68f692b01e1a1589cbfc7" source = "github.com/go-gitea/bolt" [[projects]] - digest = "1:7c96cf7bf7f52af67f7a8222185813b9b665f5172ec2ac5f7d49ed96e5fcf3e5" name = "github.com/boombuler/barcode" packages = [ ".", "qr", - "utils", + "utils" ] - pruneopts = "NUT" revision = "fe0f26ff6d26693948ee8189aa064ee8c54141fa" [[projects]] - digest = "1:867be5f6a8d3bf4525390559899af512f48675932e2cc3cbaa2304e9c75fc1ba" name = "github.com/bradfitz/gomemcache" packages = ["memcache"] - pruneopts = "NUT" revision = "fb1f79c6b65acda83063cbc69f6bba1522558bfc" [[projects]] - digest = "1:ce4ec45b1c748a187386bfb3adc6b78f07a3c6cecc689f7bf68dd0d3630c6d58" name = "github.com/chaseadamsio/goorgeous" packages = ["."] - pruneopts = "NUT" revision = "098da33fde5f9220736531b3cb26a2dec86a8367" [[projects]] branch = "master" - digest = "1:82e1ad11d777f7bff9a1fc678a8a534a318f85e5026a8a4d6f4a94a6b0678bb6" name = "github.com/couchbase/vellum" packages = [ ".", "regexp", - "utf8", + "utf8" ] - pruneopts = "NUT" revision = "eb6ae3743b3f300f2136f83ca78c08cc071edbd4" [[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "NUT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:08c314ceab5d0a82739bb0846a5d764bed6f1294610e79b651a4c08671830ecb" name = "github.com/denisenkom/go-mssqldb" packages = ["."] - pruneopts = "NUT" revision = "e32ca5036449b7ea12c62ed761ea1ad7fc88a4e2" [[projects]] - digest = "1:01ced7908dbaae42990af9521328922b8948bdcb174c23bba6db572381515716" name = "github.com/dgrijalva/jwt-go" packages = ["."] - pruneopts = "NUT" revision = "9ed569b5d1ac936e6494082958d63a6aa4fff99a" [[projects]] branch = "master" - digest = "1:7e2a28602fd65774c79a780a9c32a7a82d180e5a93bb5a36a6beb8619e24a35b" name = "github.com/edsrzf/mmap-go" packages = ["."] - pruneopts = "NUT" revision = "0bce6a6887123b67a60366d2c9fe2dfb74289d2e" [[projects]] - digest = "1:9b7f3250d2bd2c70fef82ff79a1c43cfacedd114288af3b86da0c31c67756a2f" name = "github.com/elazarl/go-bindata-assetfs" packages = ["."] - pruneopts = "NUT" revision = "57eb5e1fc594ad4b0b1dbea7b286d299e0cb43c2" [[projects]] - digest = "1:8603f74d35c93b37c615a02ba297be2cf2efc9ff6f1ff2b458a903990b568e48" name = "github.com/ethantkoenig/rupture" packages = ["."] - pruneopts = "NUT" revision = "0a76f03a811abcca2e6357329b673e9bb8ef9643" [[projects]] branch = "master" - digest = "1:b29ac3fe6b4601f89b589337c584ab7204a5c72932465e5f4a16772b5560b4a7" name = "github.com/facebookgo/clock" packages = ["."] - pruneopts = "NUT" revision = "600d898af40aa09a7a93ecb9265d87b0504b6f03" [[projects]] - digest = "1:ee3e74e7e3789fc2de1479146477b5cc31f9344dfe2772c01a967a13552c7e60" name = "github.com/facebookgo/grace" packages = [ "gracehttp", - "gracenet", + "gracenet" ] - pruneopts = "NUT" revision = "5729e484473f52048578af1b80d0008c7024089b" [[projects]] branch = "master" - digest = "1:ff3883a000118ba7efd4c41cc4656592e97d3a0860225d5f087a194066685ce4" name = "github.com/facebookgo/httpdown" packages = ["."] - pruneopts = "NUT" revision = "a3b1354551a26449fbe05f5d855937f6e7acbd71" [[projects]] branch = "master" - digest = "1:35a271df55b343e440407daac25d877269e3bb2f60d2031bcc339bcbe6c0f9b9" name = "github.com/facebookgo/stats" packages = ["."] - pruneopts = "NUT" revision = "1b76add642e42c6ffba7211ad7b3939ce654526e" [[projects]] branch = "master" - digest = "1:ccee1c7954f7296e324a0832b7a4a0a38ea7e51145375fd837283652366c3653" name = "github.com/glycerine/go-unsnap-stream" packages = ["."] - pruneopts = "NUT" revision = "9f0cb55181dd3a0a4c168d3dbc72d4aca4853126" [[projects]] branch = "master" - digest = "1:1961e20504ac246a7eacff00a56ce75cd60be05ea38e04381663593ba5879f58" name = "github.com/go-macaron/bindata" packages = ["."] - pruneopts = "NUT" revision = "85786f57eee3e5544a9cc24fa2afe425b97a8652" [[projects]] - digest = "1:628de1525ac764bbe390376679e1ee0ea538429c207926eadf66bdeccda1bf89" name = "github.com/go-macaron/binding" packages = ["."] - pruneopts = "NUT" revision = "9440f336b443056c90d7d448a0a55ad8c7599880" [[projects]] branch = "master" - digest = "1:2440f13a7c7b8a7620bf71504c41a5efb6e04a01249d4eba8b9ce00d2575e793" name = "github.com/go-macaron/cache" packages = [ ".", "memcache", - "redis", + "redis" ] - pruneopts = "NUT" revision = "56173531277692bc2925924d51fda1cd0a6b8178" [[projects]] - digest = "1:221be3922b1be8fe9405a73fd030efe0585baaa41fe9828768ac245c6ea53a83" name = "github.com/go-macaron/captcha" packages = ["."] - pruneopts = "NUT" revision = "8aa5919789ab301e865595eb4b1114d6b9847deb" [[projects]] branch = "master" - digest = "1:7ae1d1b3a156d71413b3a35ef6cf2b1fd6f91e6db0b6f1e8a5f69b47a46795d9" name = "github.com/go-macaron/csrf" packages = ["."] - pruneopts = "NUT" revision = "503617c6b37257a55dff6293ec28556506c3a9a8" [[projects]] branch = "master" - digest = "1:6326b27f8e0c8e135c8674ddbc619fae879664ac832e8e6fa6a23ce0d279ed4d" name = "github.com/go-macaron/gzip" packages = ["."] - pruneopts = "NUT" revision = "cad1c6580a07c56f5f6bc52d66002a05985c5854" [[projects]] branch = "master" - digest = "1:d09d3c94e1bd444464c221be961ba4005e119308f1bcd57aa5f49046fb6affd2" name = "github.com/go-macaron/i18n" packages = ["."] - pruneopts = "NUT" revision = "ef57533c3b0fc2d8581deda14937e52f11a203ab" [[projects]] branch = "master" - digest = "1:fb8711b648d1ff03104fc1d9593a13cb1d5120be7ba2b01641c14ccae286a9e3" name = "github.com/go-macaron/inject" packages = ["."] - pruneopts = "NUT" revision = "d8a0b8677191f4380287cfebd08e462217bac7ad" [[projects]] - digest = "1:b327ca585509a889130a8f51f43704a8fe03cb5cd281dbf1bc6405f5a7ea4702" name = "github.com/go-macaron/session" packages = [ ".", - "redis", + "redis" ] - pruneopts = "NUT" revision = "66031fcb37a0fff002a1f028eb0b3a815c78306b" [[projects]] - digest = "1:6fb9cae2a3b4518e048a899b273e23b671802b611ccfcca0b576ecc08bb7b8f5" name = "github.com/go-macaron/toolbox" packages = ["."] - pruneopts = "NUT" revision = "99a42f20e9e88daec5c0d7beb4e7eac134680ab0" [[projects]] - digest = "1:747c1fcb10f8f6734551465ab73c6ed9c551aa6e66250fb6683d1624f554546a" name = "github.com/go-sql-driver/mysql" packages = ["."] - pruneopts = "NUT" revision = "d523deb1b23d913de5bdada721a6071e71283618" [[projects]] - digest = "1:1397763fd29d5667bcfbacde8a37542ee145416b3acb7e1b149c98fef2567930" name = "github.com/go-xorm/builder" packages = ["."] - pruneopts = "NUT" revision = "dc8bf48f58fab2b4da338ffd25191905fd741b8f" version = "v0.3.0" [[projects]] - digest = "1:c910feae32bcc3cbf068c7263424d9f198da931c0cad909179621835e6f87cb8" name = "github.com/go-xorm/core" packages = ["."] - pruneopts = "NUT" revision = "c10e21e7e1cec20e09398f2dfae385e58c8df555" version = "v0.6.0" [[projects]] - digest = "1:22a1ac7f654095f6817076eb975368bab5481e42554d0121ea37e28a86a3f83d" name = "github.com/go-xorm/xorm" packages = ["."] - pruneopts = "NUT" revision = "ad69f7d8f0861a29438154bb0a20b60501298480" [[projects]] branch = "master" - digest = "1:5fdcd55bad5c103674364f4fdb1ad2541186d063300ab24a8f2bb1b31ae07bac" name = "github.com/gogits/chardet" packages = ["."] - pruneopts = "NUT" revision = "2404f777256163ea3eadb273dada5dcb037993c0" [[projects]] - digest = "1:ea030ad2f50b1ced1944914dd80c72e9ebd839fb564c7b8859e7a5d626c61c51" name = "github.com/gogits/cron" packages = ["."] - pruneopts = "NUT" revision = "7f3990acf1833faa5ebd0e86f0a4c72a4b5eba3c" [[projects]] - digest = "1:b64f9be717fdab5f75122dc3868e8ca9d003779b6bc55f64f39a0cddc698bf88" name = "github.com/golang/protobuf" packages = ["proto"] - pruneopts = "NUT" revision = "99511271042a09d1e01baea8781caa5210fec66e" [[projects]] - digest = "1:60e25fc5f5cfd7783f985ca99b4383e848981dddf0be584db7d809be20848e25" name = "github.com/golang/snappy" packages = ["."] - pruneopts = "NUT" revision = "5f1c01d9f64b941dd9582c638279d046eda6ca31" [[projects]] - digest = "1:c01767916c59f084bb7c41a7d5877c0f3099b1595cfa066e84ec6ad6b084dd89" name = "github.com/gorilla/context" packages = ["."] - pruneopts = "NUT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - digest = "1:9ad9280c98033812aec525d43d4e8137021642dc942bf271b4710f9ac93d0d0b" name = "github.com/gorilla/mux" packages = ["."] - pruneopts = "NUT" revision = "757bef944d0f21880861c2dd9c871ca543023cba" [[projects]] - digest = "1:0faa8131e5822f3420f82426667a29c5c425c3cb7e0fcf0c5d1c718d6e6ba19b" name = "github.com/gorilla/securecookie" packages = ["."] - pruneopts = "NUT" revision = "e59506cc896acb7f7bf732d4fdf5e25f7ccd8983" version = "v1.1.1" [[projects]] - digest = "1:ee5531f1e32c0082a6da68a605bc60284711d99b15d38dfba335a1ec52a58c20" name = "github.com/gorilla/sessions" packages = ["."] - pruneopts = "NUT" revision = "ca9ada44574153444b00d3fd9c8559e4cc95f896" version = "v1.1" [[projects]] - digest = "1:18231f2a4af6633fbcd94baab40320d16e826a7f732094ba3420ab547206949b" name = "github.com/issue9/identicon" packages = ["."] - pruneopts = "NUT" revision = "d36b54562f4cf70c83653e13dc95c220c79ef521" [[projects]] - digest = "1:d2d4f736f81c5312e2b885798f8a33f9819c6217664404d5b9a4088fcd606df4" name = "github.com/jaytaylor/html2text" packages = ["."] - pruneopts = "NUT" revision = "8fb95d837f7d6db1913fecfd7bcc5333e6499596" [[projects]] - digest = "1:6342cf70eaae592f7b8e2552037f2a9d4d16fa321c6e36f09c3bc450add2de19" name = "github.com/kballard/go-shellquote" packages = ["."] - pruneopts = "NUT" revision = "cd60e84ee657ff3dc51de0b4f55dd299a3e136f2" [[projects]] - digest = "1:b32126992771fddadf6a778fe7ab29150665ed78f31ce4eb550a9db3bc0e650c" name = "github.com/keybase/go-crypto" packages = [ "brainpool", @@ -485,69 +376,55 @@ "openpgp/errors", "openpgp/packet", "openpgp/s2k", - "rsa", + "rsa" ] - pruneopts = "NUT" revision = "00ac4db533f63ef97576cbc7b07939ff7daf7329" [[projects]] - digest = "1:c5e37ea5ada80299e6a8e7ebc1a47999c2c8a53eac3a455168adcdcdc78dc93a" name = "github.com/klauspost/compress" packages = [ "flate", - "gzip", + "gzip" ] - pruneopts = "NUT" revision = "8df558b6cb6f9b445f9586446cfe7223e7d8bd6b" version = "v1.1" [[projects]] - digest = "1:6a2949d9a141c72cfaa5b55c65794d9b1179878fccdcae735ab62be27bf9cf34" name = "github.com/klauspost/cpuid" packages = ["."] - pruneopts = "NUT" revision = "09cded8978dc9e80714c4d85b0322337b0a1e5e0" version = "v1.0" [[projects]] - digest = "1:b95da1293525625ef6f07be79d537b9bf2ecd7901efcf9a92193edafbd55b9ef" name = "github.com/klauspost/crc32" packages = ["."] - pruneopts = "NUT" revision = "cb6bfca970f6908083f26f39a79009d608efd5cd" version = "v1.1" [[projects]] - digest = "1:38fc7fe0f78eaecdf1ab39a60ba49df85405597103f38d07f2ac560e7e4c8443" name = "github.com/lafriks/xormstore" packages = [ ".", - "util", + "util" ] - pruneopts = "NUT" revision = "9cab149ea91875cf056211bd6ef82379fce9cb67" version = "v1.0.0" [[projects]] - digest = "1:f1105223bc7ff6a3f3074cf6cccc6c8362ff23db1e7d8505dda01fc4b79b8005" name = "github.com/lib/pq" packages = [ ".", - "oid", + "oid" ] - pruneopts = "NUT" revision = "456514e2defec52e0cd37f90ccf17ec8b28295e2" [[projects]] branch = "master" - digest = "1:6e81c70f78cdc298ea6f19fa9bdba95aacd13a0e0ddb7e118046113997d4dafb" name = "github.com/lunny/dingtalk_webhook" packages = ["."] - pruneopts = "NUT" revision = "e3534c89ef969912856dfa39e56b09e58c5f5daf" [[projects]] - digest = "1:fb22af9d8c1a6166ad299705648db460ba2c28a830f7f6cdd830019d7c3fd96f" name = "github.com/markbates/goth" packages = [ ".", @@ -559,175 +436,131 @@ "providers/gitlab", "providers/gplus", "providers/openidConnect", - "providers/twitter", + "providers/twitter" ] - pruneopts = "NUT" revision = "4933f155d89c3c52ab4ca545c6602cf4a1e87913" version = "1.45.5" [[projects]] - digest = "1:3ef954101983406a71171c4dc816a73e01bb3de608b3dd063627aa67a459f3e3" name = "github.com/mattn/go-sqlite3" packages = ["."] - pruneopts = "NUT" revision = "acfa60124032040b9f5a9406f5a772ee16fe845e" [[projects]] branch = "master" - digest = "1:1ed0f3c066eb9d1c2ff7a864a6fa595c70b9b49049cc46af6a6f7ff0e4655321" name = "github.com/mcuadros/go-version" packages = ["."] - pruneopts = "NUT" revision = "88e56e02bea1c203c99222c365fa52a69996ccac" [[projects]] - digest = "1:f2111ff3f139dacf8b2177e32f296ad20df85d6ec0ee0e2e348f0fcb21186c14" name = "github.com/microcosm-cc/bluemonday" packages = ["."] - pruneopts = "NUT" revision = "f77f16ffc87a6a58814e64ae72d55f9c41374e6d" [[projects]] - digest = "1:c7dc71a7e144df03332152d730f9c5ae22cf1cfd55454cb001ba8ffcb78aa7f0" name = "github.com/mrjones/oauth" packages = ["."] - pruneopts = "NUT" revision = "3f67d9c274355678b2f9844b08d643e2f9213340" [[projects]] branch = "master" - digest = "1:874d20d479aa479b2ed0200ac565e809d8ff849f672a04e7a21536069eba1cdd" name = "github.com/mschoch/smat" packages = ["."] - pruneopts = "NUT" revision = "90eadee771aeab36e8bf796039b8c261bebebe4f" [[projects]] - digest = "1:15bc31ae39f989dda613930c1de860aced7b922502f8d9d861998fc195b7937c" name = "github.com/msteinert/pam" packages = ["."] - pruneopts = "NUT" revision = "02ccfbfaf0cc627aa3aec8ef7ed5cfeec5b43f63" [[projects]] - digest = "1:2be1d891535ce3d6d2a3db9087f07415e909744e9eff1a30f8f0b2519df60ae6" name = "github.com/nfnt/resize" packages = ["."] - pruneopts = "NUT" revision = "891127d8d1b52734debe1b3c3d7e747502b6c366" [[projects]] - digest = "1:44c66ad69563dbe3f8e76d7d6cad21a03626e53f1875b5ab163ded419e01ca7a" name = "github.com/philhofer/fwd" packages = ["."] - pruneopts = "NUT" revision = "bb6d471dc95d4fe11e432687f8b70ff496cf3136" version = "v1.0.0" [[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" name = "github.com/pmezard/go-difflib" packages = ["difflib"] - pruneopts = "NUT" revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" [[projects]] - digest = "1:aabb118251a9ee8ddab44c405f2391852a82dcf33358cda25ea5748561411ffc" name = "github.com/pquerna/otp" packages = [ ".", "hotp", - "totp", + "totp" ] - pruneopts = "NUT" revision = "54653902c20e47f3417541d35435cb6d6162e28a" [[projects]] branch = "master" - digest = "1:5be01c22bc1040e2f6ce4755d51a0ac9cef823a9f2004fb1f9896a414ef519e6" name = "github.com/russross/blackfriday" packages = ["."] - pruneopts = "NUT" revision = "11635eb403ff09dbc3a6b5a007ab5ab09151c229" [[projects]] - digest = "1:54f275b550b8a8a20bc91e2067ed740600b69dae9dcf9cdfe905bac1b9cfd1d0" name = "github.com/satori/go.uuid" packages = ["."] - pruneopts = "NUT" revision = "b061729afc07e77a8aa4fad0a2fd840958f1942a" [[projects]] - digest = "1:3e0777ad56c86a93cf22459acca84d5c3c8a86b163362074dcb7b33c01aba82b" name = "github.com/sergi/go-diff" packages = ["diffmatchpatch"] - pruneopts = "NUT" revision = "552b4e9bbdca9e5adafd95ee98c822fdd11b330b" [[projects]] - digest = "1:400359f0b394fb168f4aee9621d42cc005810c6e462009d5fc76055d5e96dcf3" name = "github.com/shurcooL/sanitized_anchor_name" packages = ["."] - pruneopts = "NUT" revision = "1dba4b3954bc059efc3991ec364f9f9a35f597d2" [[projects]] branch = "master" - digest = "1:69177343ca227319b4580441a67d9d889e9ac7fcbfb89fbaa36d3283e6ab0139" name = "github.com/steveyen/gtreap" packages = ["."] - pruneopts = "NUT" revision = "0abe01ef9be25c4aedc174758ec2d917314d6d70" [[projects]] - digest = "1:a852b1ad03ca063d2c57866d9f94dcb1cb2e111415c5902ce0586fc2d207221b" name = "github.com/stretchr/testify" packages = ["assert"] - pruneopts = "NUT" revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" version = "v1.2.1" [[projects]] branch = "master" - digest = "1:3cb6dfe7cdece5716b1c3c3c0b5faf7fce2e83e2758e2baad2e9986d101980b8" name = "github.com/tinylib/msgp" packages = ["msgp"] - pruneopts = "NUT" revision = "c8cf64dff2009d53fa8f8a16df54d1cdfc64c4a7" [[projects]] branch = "master" - digest = "1:aa8ce6454cff67af88a195977ba6489df6c55802e1199cbe24af9febec8c1586" name = "github.com/tstranex/u2f" packages = ["."] - pruneopts = "NUT" revision = "d21a03e0b1d9fc1df59ff54e7a513655c1748b0c" [[projects]] - digest = "1:d9f3ecc1fb41eaf8af777f844a2c0eb9b7ff743224981e5af4ade023210cf6e5" name = "github.com/urfave/cli" packages = ["."] - pruneopts = "NUT" revision = "d86a009f5e13f83df65d0d6cee9a2e3f1445f0da" [[projects]] branch = "master" - digest = "1:1d786f876a94d808e0ee5052e1f65ab284dc7483a7517d76d25baa8099429ed5" name = "github.com/willf/bitset" packages = ["."] - pruneopts = "NUT" revision = "8ce1146b8621c95164efd9c8b1124cfa9b8afb4e" [[projects]] - digest = "1:27d050258a4b19ca3b7a1bf26f4a04c5c66bbf0670b346ee509ebb0ad82257a6" name = "github.com/yohcop/openid-go" packages = ["."] - pruneopts = "NUT" revision = "2c050d2dae5345c417db301f11fda6fbf5ad0f0a" [[projects]] - digest = "1:e4ea859df4986eb46feebbb84a2d163a4a314e87668177ca13b3b0adecaf50e8" name = "golang.org/x/crypto" packages = [ "acme", @@ -739,53 +572,43 @@ "md4", "pbkdf2", "poly1305", - "ssh", + "ssh" ] - pruneopts = "NUT" revision = "12dd70caea0268ac0d6c2707d0611ef601e7c64e" [[projects]] - digest = "1:47ea747d07fae720d749d06ac5dc5ded0df70c57e328b6549cf2d9c64698757e" name = "golang.org/x/net" packages = [ "context", "html", "html/atom", - "html/charset", + "html/charset" ] - pruneopts = "NUT" revision = "f2499483f923065a842d38eb4c7f1927e6fc6e6d" [[projects]] - digest = "1:8159a9cda4b8810aaaeb0d60e2fa68e2fd86d8af4ec8f5059830839e3c8d93d5" name = "golang.org/x/oauth2" packages = [ ".", - "internal", + "internal" ] - pruneopts = "NUT" revision = "c10ba270aa0bf8b8c1c986e103859c67a9103061" [[projects]] - digest = "1:9f303486d623f840492bfeb48eb906a94e9d3fe638a761639b72ce64bf7bfcc3" name = "golang.org/x/sync" packages = ["syncmap"] - pruneopts = "NUT" revision = "5a06fca2c336a4b2b2fcb45702e8c47621b2aa2c" [[projects]] - digest = "1:47495898c42062ace16d8046915b088e7c3846e77b997ec5a8a00ec552e179d5" name = "golang.org/x/sys" packages = [ "unix", "windows", - "windows/svc", + "windows/svc" ] - pruneopts = "NUT" revision = "a646d33e2ee3172a661fc09bca23bb4889a41bc8" [[projects]] - digest = "1:d2463fd72ee2636c3d9bbdb98fa4996a118f210ae3e5eaf62d281855bc0b4a83" name = "golang.org/x/text" packages = [ "encoding", @@ -807,200 +630,83 @@ "runes", "transform", "unicode/cldr", - "unicode/norm", + "unicode/norm" ] - pruneopts = "NUT" revision = "2bf8f2a19ec09c670e931282edfe6567f6be21c9" [[projects]] branch = "v3" - digest = "1:1244a9b3856f70d5ffb74bbfd780fc9d47f93f2049fa265c6fb602878f507bf8" name = "gopkg.in/alexcesaro/quotedprintable.v3" packages = ["."] - pruneopts = "NUT" revision = "2caba252f4dc53eaf6b553000885530023f54623" [[projects]] - digest = "1:9c577b4736db46066c2a41aef5736316fc5e0c8d1b97e8917f4b6157b530ee53" name = "gopkg.in/asn1-ber.v1" packages = ["."] - pruneopts = "NUT" revision = "4e86f4367175e39f69d9358a5f17b4dda270378d" version = "v1.1" [[projects]] - digest = "1:24bfc2e8bf971485cb5ba0f0e5b08a1b806cca5828134df76b32d1ea50f2ab49" name = "gopkg.in/bufio.v1" packages = ["."] - pruneopts = "NUT" revision = "567b2bfa514e796916c4747494d6ff5132a1dfce" version = "v1" [[projects]] - digest = "1:9146e4250cb4359ac2f7a1ac3766dbcc52b3d8414ab9ac1af195ce6fba6c234f" name = "gopkg.in/editorconfig/editorconfig-core-go.v1" packages = ["."] - pruneopts = "NUT" revision = "a872f05c2e34b37b567401384d202aff11ba06d4" version = "v1.2.0" [[projects]] branch = "v2" - digest = "1:8db3ee13f824cd299f10af1dead41de8bce6b53a704998976e58c5b9274ab4b6" name = "gopkg.in/gomail.v2" packages = ["."] - pruneopts = "NUT" revision = "81ebce5c23dfd25c6c67194b37d3dd3f338c98b1" [[projects]] - digest = "1:cbecb8d0e314f34d1bc65a86cb433e33ad8e32c2cb6ae313a4f2e52806ddd984" name = "gopkg.in/ini.v1" packages = ["."] - pruneopts = "NUT" revision = "7e7da451323b6766da368f8a1e8ec9a88a16b4a0" version = "v1.31.1" [[projects]] - digest = "1:01f4ac37c52bda6f7e1bd73680a99f88733c0408aaa159ecb1ba53a1ade9423c" name = "gopkg.in/ldap.v2" packages = ["."] - pruneopts = "NUT" revision = "d0a5ced67b4dc310b9158d63a2c6f9c5ec13f105" version = "v2.4.1" [[projects]] - digest = "1:cfe1730a152ff033ad7d9c115d22e36b19eec6d5928c06146b9119be45d39dc0" name = "gopkg.in/macaron.v1" packages = ["."] - pruneopts = "NUT" revision = "75f2e9b42e99652f0d82b28ccb73648f44615faa" version = "v1.2.4" [[projects]] - digest = "1:00126f697efdcab42f07c89ac8bf0095fb2328aef6464e070055154088cea859" name = "gopkg.in/redis.v2" packages = ["."] - pruneopts = "NUT" revision = "e6179049628164864e6e84e973cfb56335748dea" version = "v2.3.2" [[projects]] - digest = "1:e2144032dcf8e856fb733151391669dc2d32d79ebb69e3c4151efa605f5e8a01" name = "gopkg.in/testfixtures.v2" packages = ["."] - pruneopts = "NUT" revision = "b9ef14dc461bf934d8df2dfc6f1f456be5664cca" version = "v2.0.0" [[projects]] - digest = "1:ad6f94355d292690137613735965bd3688844880fdab90eccf66321910344942" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "NUT" revision = "a5b47d31c556af34a302ce5d659e6fea44d90de0" [[projects]] - digest = "1:5972c0a5308529a35d87dd2dbba827625df90e6c89b0f496644fc43ea761bcf2" name = "strk.kbt.io/projects/go/libravatar" packages = ["."] - pruneopts = "NUT" revision = "5eed7bff870ae19ef51c5773dbc8f3e9fcbd0982" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "code.gitea.io/git", - "code.gitea.io/sdk/gitea", - "github.com/PuerkitoBio/goquery", - "github.com/Unknwon/cae/zip", - "github.com/Unknwon/com", - "github.com/Unknwon/i18n", - "github.com/Unknwon/paginater", - "github.com/blevesearch/bleve", - "github.com/blevesearch/bleve/analysis/analyzer/custom", - "github.com/blevesearch/bleve/analysis/token/camelcase", - "github.com/blevesearch/bleve/analysis/token/lowercase", - "github.com/blevesearch/bleve/analysis/token/unicodenorm", - "github.com/blevesearch/bleve/analysis/token/unique", - "github.com/blevesearch/bleve/analysis/tokenizer/unicode", - "github.com/blevesearch/bleve/index/upsidedown", - "github.com/blevesearch/bleve/mapping", - "github.com/blevesearch/bleve/search/query", - "github.com/chaseadamsio/goorgeous", - "github.com/denisenkom/go-mssqldb", - "github.com/dgrijalva/jwt-go", - "github.com/ethantkoenig/rupture", - "github.com/facebookgo/grace/gracehttp", - "github.com/go-macaron/bindata", - "github.com/go-macaron/binding", - "github.com/go-macaron/cache", - "github.com/go-macaron/cache/memcache", - "github.com/go-macaron/cache/redis", - "github.com/go-macaron/captcha", - "github.com/go-macaron/csrf", - "github.com/go-macaron/gzip", - "github.com/go-macaron/i18n", - "github.com/go-macaron/inject", - "github.com/go-macaron/session", - "github.com/go-macaron/session/redis", - "github.com/go-macaron/toolbox", - "github.com/go-sql-driver/mysql", - "github.com/go-xorm/builder", - "github.com/go-xorm/core", - "github.com/go-xorm/xorm", - "github.com/gogits/chardet", - "github.com/gogits/cron", - "github.com/gorilla/context", - "github.com/issue9/identicon", - "github.com/jaytaylor/html2text", - "github.com/kballard/go-shellquote", - "github.com/keybase/go-crypto/openpgp", - "github.com/keybase/go-crypto/openpgp/armor", - "github.com/keybase/go-crypto/openpgp/packet", - "github.com/lafriks/xormstore", - "github.com/lib/pq", - "github.com/lunny/dingtalk_webhook", - "github.com/markbates/goth", - "github.com/markbates/goth/gothic", - "github.com/markbates/goth/providers/bitbucket", - "github.com/markbates/goth/providers/dropbox", - "github.com/markbates/goth/providers/facebook", - "github.com/markbates/goth/providers/github", - "github.com/markbates/goth/providers/gitlab", - "github.com/markbates/goth/providers/gplus", - "github.com/markbates/goth/providers/openidConnect", - "github.com/markbates/goth/providers/twitter", - "github.com/mattn/go-sqlite3", - "github.com/mcuadros/go-version", - "github.com/microcosm-cc/bluemonday", - "github.com/msteinert/pam", - "github.com/nfnt/resize", - "github.com/pquerna/otp", - "github.com/pquerna/otp/totp", - "github.com/russross/blackfriday", - "github.com/satori/go.uuid", - "github.com/sergi/go-diff/diffmatchpatch", - "github.com/stretchr/testify/assert", - "github.com/tstranex/u2f", - "github.com/urfave/cli", - "github.com/yohcop/openid-go", - "golang.org/x/crypto/acme/autocert", - "golang.org/x/crypto/pbkdf2", - "golang.org/x/crypto/ssh", - "golang.org/x/net/html", - "golang.org/x/net/html/atom", - "golang.org/x/net/html/charset", - "golang.org/x/sync/syncmap", - "golang.org/x/sys/windows/svc", - "golang.org/x/text/transform", - "gopkg.in/editorconfig/editorconfig-core-go.v1", - "gopkg.in/gomail.v2", - "gopkg.in/ini.v1", - "gopkg.in/ldap.v2", - "gopkg.in/macaron.v1", - "gopkg.in/testfixtures.v2", - "strk.kbt.io/projects/go/libravatar", - ] + inputs-digest = "630dc9899a6e4c41863a8fa5c00b2017bc5bca748e3fad813bf8c3b8602a0d9f" solver-name = "gps-cdcl" solver-version = 1 From 4d1adedb26d9c1276cb29411fd0c8deeb355cd70 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 23 Jan 2019 21:48:20 -0500 Subject: [PATCH 18/21] Update type & add copyright --- models/issue.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/models/issue.go b/models/issue.go index 7ca8682802eb7..5e3d2bae028d9 100644 --- a/models/issue.go +++ b/models/issue.go @@ -1,4 +1,5 @@ // 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. @@ -36,7 +37,7 @@ type Issue struct { Labels []*Label `xorm:"-"` MilestoneID int64 `xorm:"INDEX"` Milestone *Milestone `xorm:"-"` - Priority int `xorm:"priority"` // Indicates priority in list display + Priority int64 `xorm:"priority"` // Indicates priority in list display AssigneeID int64 `xorm:"-"` Assignee *User `xorm:"-"` IsClosed bool `xorm:"INDEX"` From 5d9ce316fd8a7711a39b27b82505dab17888236f Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 23 Jan 2019 21:53:11 -0500 Subject: [PATCH 19/21] Update type & add copyright --- models/error.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/models/error.go b/models/error.go index 7a8d5046a3ac3..23d164c615520 100644 --- a/models/error.go +++ b/models/error.go @@ -1,4 +1,5 @@ // 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. @@ -881,7 +882,7 @@ func (err ErrIssueNotExist) Error() string { type ErrIssueInvalidPriority struct { ID int64 RepoID int64 - DesiredPriority int + DesiredPriority int64 } // IsErrIssueInvalidPriority checks if an error is a ErrIssueInvalidPriority. From db32f2a92f58b80fc6f21be6c037b3c63aa7b50b Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 23 Jan 2019 22:11:10 -0500 Subject: [PATCH 20/21] Update issuse_priority.go --- models/issuse_priority.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/issuse_priority.go b/models/issuse_priority.go index f4d677bd5ebe3..9b1d07957adbf 100644 --- a/models/issuse_priority.go +++ b/models/issuse_priority.go @@ -36,7 +36,7 @@ func PinIssue(issue *Issue, doer *User) error { return err } - if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil { + if has, err := HasAccess(doer.ID, issue.Repo); err != nil { return err } else if !has { return ErrUserDoesNotHaveAccessToRepo{UserID: doer.ID, RepoName: issue.Repo.Name} From 300b19e1beaa0eb5ffb021d9b0def000e5f9ad57 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 23 Jan 2019 22:13:57 -0500 Subject: [PATCH 21/21] Update type --- modules/auth/repo_form.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/auth/repo_form.go b/modules/auth/repo_form.go index ea2b01c284486..7c4b302a990ee 100644 --- a/modules/auth/repo_form.go +++ b/modules/auth/repo_form.go @@ -295,7 +295,7 @@ type CreateCommentForm struct { // EditPriorityForm form for updating priority type EditPriorityForm struct { // required:true - Priority int `binding:"Required;Range(1,5)"` + Priority int64 `binding:"Required;Range(1,5)"` } // Validate validates the fields