Move create release from models to a standalone package (#7539)

* move create release from models to a standalone package

* fix lint

* fix comment year

* fix lint

* fix lint

* fix package import name

* fix vendor

* fix go mod

* some refactors

* fix vendor

* use go1.12 make vendor

* fix vendor
This commit is contained in:
Lunny Xiao 2019-09-15 23:28:25 +08:00 committed by GitHub
parent be0f7ff9bf
commit 4959bf1c09
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 191 additions and 147 deletions

View file

@ -112,43 +112,20 @@ func IsReleaseExist(repoID int64, tagName string) (bool, error) {
return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}) return x.Get(&Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)})
} }
func createTag(gitRepo *git.Repository, rel *Release) error { // InsertRelease inserts a release
// Only actual create when publish. func InsertRelease(rel *Release) error {
if !rel.IsDraft { _, err := x.Insert(rel)
if !gitRepo.IsTagExist(rel.TagName) {
commit, err := gitRepo.GetCommit(rel.Target)
if err != nil {
return fmt.Errorf("GetCommit: %v", err)
}
// Trim '--' prefix to prevent command line argument vulnerability.
rel.TagName = strings.TrimPrefix(rel.TagName, "--")
if err = gitRepo.CreateTag(rel.TagName, commit.ID.String()); err != nil {
if strings.Contains(err.Error(), "is not a valid tag name") {
return ErrInvalidTagName{rel.TagName}
}
return err return err
} }
rel.LowerTagName = strings.ToLower(rel.TagName)
} // UpdateRelease updates all columns of a release
commit, err := gitRepo.GetTagCommit(rel.TagName) func UpdateRelease(rel *Release) error {
if err != nil { _, err := x.ID(rel.ID).AllCols().Update(rel)
return fmt.Errorf("GetTagCommit: %v", err) return err
} }
rel.Sha1 = commit.ID.String() // AddReleaseAttachments adds a release attachments
rel.CreatedUnix = timeutil.TimeStamp(commit.Author.When.Unix()) func AddReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
rel.NumCommits, err = commit.CommitsCount()
if err != nil {
return fmt.Errorf("CommitsCount: %v", err)
}
} else {
rel.CreatedUnix = timeutil.TimeStampNow()
}
return nil
}
func addReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error) {
// Check attachments // Check attachments
var attachments = make([]*Attachment, 0) var attachments = make([]*Attachment, 0)
for _, uuid := range attachmentUUIDs { for _, uuid := range attachmentUUIDs {
@ -173,51 +150,6 @@ func addReleaseAttachments(releaseID int64, attachmentUUIDs []string) (err error
return return
} }
// CreateRelease creates a new release of repository.
func CreateRelease(gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) error {
isExist, err := IsReleaseExist(rel.RepoID, rel.TagName)
if err != nil {
return err
} else if isExist {
return ErrReleaseAlreadyExist{rel.TagName}
}
if err = createTag(gitRepo, rel); err != nil {
return err
}
rel.LowerTagName = strings.ToLower(rel.TagName)
_, err = x.InsertOne(rel)
if err != nil {
return err
}
err = addReleaseAttachments(rel.ID, attachmentUUIDs)
if err != nil {
return err
}
if !rel.IsDraft {
if err := rel.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
} else {
mode, _ := AccessLevel(rel.Publisher, rel.Repo)
if err := PrepareWebhooks(rel.Repo, HookEventRelease, &api.ReleasePayload{
Action: api.HookReleasePublished,
Release: rel.APIFormat(),
Repository: rel.Repo.APIFormat(mode),
Sender: rel.Publisher.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
} else {
go HookQueue.Add(rel.Repo.ID)
}
}
}
return nil
}
// GetRelease returns release by given ID. // GetRelease returns release by given ID.
func GetRelease(repoID int64, tagName string) (*Release, error) { func GetRelease(repoID int64, tagName string) (*Release, error) {
isExist, err := IsReleaseExist(repoID, tagName) isExist, err := IsReleaseExist(repoID, tagName)
@ -385,40 +317,6 @@ func SortReleases(rels []*Release) {
sort.Sort(sorter) sort.Sort(sorter)
} }
// UpdateRelease updates information of a release.
func UpdateRelease(doer *User, gitRepo *git.Repository, rel *Release, attachmentUUIDs []string) (err error) {
if err = createTag(gitRepo, rel); err != nil {
return err
}
rel.LowerTagName = strings.ToLower(rel.TagName)
_, err = x.ID(rel.ID).AllCols().Update(rel)
if err != nil {
return err
}
err = rel.loadAttributes(x)
if err != nil {
return err
}
err = addReleaseAttachments(rel.ID, attachmentUUIDs)
mode, _ := AccessLevel(doer, rel.Repo)
if err1 := PrepareWebhooks(rel.Repo, HookEventRelease, &api.ReleasePayload{
Action: api.HookReleaseUpdated,
Release: rel.APIFormat(),
Repository: rel.Repo.APIFormat(mode),
Sender: doer.APIFormat(),
}); err1 != nil {
log.Error("PrepareWebhooks: %v", err)
} else {
go HookQueue.Add(rel.Repo.ID)
}
return err
}
// DeleteReleaseByID deletes a release and corresponding Git tag by given ID. // DeleteReleaseByID deletes a release and corresponding Git tag by given ID.
func DeleteReleaseByID(id int64, doer *User, delTag bool) error { func DeleteReleaseByID(id int64, doer *User, delTag bool) error {
rel, err := GetReleaseByID(id) rel, err := GetReleaseByID(id)

View file

@ -318,6 +318,12 @@ func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
return parseRemoteUpdateOutput(output), true return parseRemoteUpdateOutput(output), true
} }
// RunMirrorSync will invoke Mirror's runSync
func RunMirrorSync(mirror *Mirror) bool {
_, ok := mirror.runSync()
return ok
}
func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) { func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
m := &Mirror{RepoID: repoID} m := &Mirror{RepoID: repoID}
has, err := e.Get(m) has, err := e.Get(m)

View file

@ -9,6 +9,7 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
releaseservice "code.gitea.io/gitea/services/release"
) )
// GetRelease get a single release of a repository // GetRelease get a single release of a repository
@ -168,7 +169,7 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) {
IsTag: false, IsTag: false,
Repo: ctx.Repo.Repository, Repo: ctx.Repo.Repository,
} }
if err := models.CreateRelease(ctx.Repo.GitRepo, rel, nil); err != nil { if err := releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, nil); err != nil {
if models.IsErrReleaseAlreadyExist(err) { if models.IsErrReleaseAlreadyExist(err) {
ctx.Status(409) ctx.Status(409)
} else { } else {
@ -191,7 +192,7 @@ func CreateRelease(ctx *context.APIContext, form api.CreateReleaseOption) {
rel.Repo = ctx.Repo.Repository rel.Repo = ctx.Repo.Repository
rel.Publisher = ctx.User rel.Publisher = ctx.User
if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil { if err = releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil {
ctx.ServerError("UpdateRelease", err) ctx.ServerError("UpdateRelease", err)
return return
} }
@ -262,7 +263,7 @@ func EditRelease(ctx *context.APIContext, form api.EditReleaseOption) {
if form.IsPrerelease != nil { if form.IsPrerelease != nil {
rel.IsPrerelease = *form.IsPrerelease rel.IsPrerelease = *form.IsPrerelease
} }
if err := models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil { if err := releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, nil); err != nil {
ctx.Error(500, "UpdateRelease", err) ctx.Error(500, "UpdateRelease", err)
return return
} }

View file

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/markup/markdown"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
releaseservice "code.gitea.io/gitea/services/release"
) )
const ( const (
@ -175,7 +176,7 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
IsTag: false, IsTag: false,
} }
if err = models.CreateRelease(ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil { if err = releaseservice.CreateRelease(ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil {
ctx.Data["Err_TagName"] = true ctx.Data["Err_TagName"] = true
switch { switch {
case models.IsErrReleaseAlreadyExist(err): case models.IsErrReleaseAlreadyExist(err):
@ -202,7 +203,7 @@ func NewReleasePost(ctx *context.Context, form auth.NewReleaseForm) {
rel.PublisherID = ctx.User.ID rel.PublisherID = ctx.User.ID
rel.IsTag = false rel.IsTag = false
if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil { if err = releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil {
ctx.Data["Err_TagName"] = true ctx.Data["Err_TagName"] = true
ctx.ServerError("UpdateRelease", err) ctx.ServerError("UpdateRelease", err)
return return
@ -281,7 +282,7 @@ func EditReleasePost(ctx *context.Context, form auth.EditReleaseForm) {
rel.Note = form.Content rel.Note = form.Content
rel.IsDraft = len(form.Draft) > 0 rel.IsDraft = len(form.Draft) > 0
rel.IsPrerelease = form.Prerelease rel.IsPrerelease = form.Prerelease
if err = models.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil { if err = releaseservice.UpdateRelease(ctx.User, ctx.Repo.GitRepo, rel, attachmentUUIDs); err != nil {
ctx.ServerError("UpdateRelease", err) ctx.ServerError("UpdateRelease", err)
return return
} }

132
services/release/release.go Normal file
View file

@ -0,0 +1,132 @@
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package release
import (
"fmt"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil"
)
func createTag(gitRepo *git.Repository, rel *models.Release) error {
// Only actual create when publish.
if !rel.IsDraft {
if !gitRepo.IsTagExist(rel.TagName) {
commit, err := gitRepo.GetCommit(rel.Target)
if err != nil {
return fmt.Errorf("GetCommit: %v", err)
}
// Trim '--' prefix to prevent command line argument vulnerability.
rel.TagName = strings.TrimPrefix(rel.TagName, "--")
if err = gitRepo.CreateTag(rel.TagName, commit.ID.String()); err != nil {
if strings.Contains(err.Error(), "is not a valid tag name") {
return models.ErrInvalidTagName{
TagName: rel.TagName,
}
}
return err
}
rel.LowerTagName = strings.ToLower(rel.TagName)
}
commit, err := gitRepo.GetTagCommit(rel.TagName)
if err != nil {
return fmt.Errorf("GetTagCommit: %v", err)
}
rel.Sha1 = commit.ID.String()
rel.CreatedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
rel.NumCommits, err = commit.CommitsCount()
if err != nil {
return fmt.Errorf("CommitsCount: %v", err)
}
} else {
rel.CreatedUnix = timeutil.TimeStampNow()
}
return nil
}
// CreateRelease creates a new release of repository.
func CreateRelease(gitRepo *git.Repository, rel *models.Release, attachmentUUIDs []string) error {
isExist, err := models.IsReleaseExist(rel.RepoID, rel.TagName)
if err != nil {
return err
} else if isExist {
return models.ErrReleaseAlreadyExist{
TagName: rel.TagName,
}
}
if err = createTag(gitRepo, rel); err != nil {
return err
}
rel.LowerTagName = strings.ToLower(rel.TagName)
if err = models.InsertRelease(rel); err != nil {
return err
}
if err = models.AddReleaseAttachments(rel.ID, attachmentUUIDs); err != nil {
return err
}
if !rel.IsDraft {
if err := rel.LoadAttributes(); err != nil {
log.Error("LoadAttributes: %v", err)
} else {
mode, _ := models.AccessLevel(rel.Publisher, rel.Repo)
if err := models.PrepareWebhooks(rel.Repo, models.HookEventRelease, &api.ReleasePayload{
Action: api.HookReleasePublished,
Release: rel.APIFormat(),
Repository: rel.Repo.APIFormat(mode),
Sender: rel.Publisher.APIFormat(),
}); err != nil {
log.Error("PrepareWebhooks: %v", err)
} else {
go models.HookQueue.Add(rel.Repo.ID)
}
}
}
return nil
}
// UpdateRelease updates information of a release.
func UpdateRelease(doer *models.User, gitRepo *git.Repository, rel *models.Release, attachmentUUIDs []string) (err error) {
if err = createTag(gitRepo, rel); err != nil {
return err
}
rel.LowerTagName = strings.ToLower(rel.TagName)
if err = models.UpdateRelease(rel); err != nil {
return err
}
if err = rel.LoadAttributes(); err != nil {
return err
}
err = models.AddReleaseAttachments(rel.ID, attachmentUUIDs)
// even if attachments added failed, hooks will be still triggered
mode, _ := models.AccessLevel(doer, rel.Repo)
if err1 := models.PrepareWebhooks(rel.Repo, models.HookEventRelease, &api.ReleasePayload{
Action: api.HookReleaseUpdated,
Release: rel.APIFormat(),
Repository: rel.Repo.APIFormat(mode),
Sender: doer.APIFormat(),
}); err1 != nil {
log.Error("PrepareWebhooks: %v", err)
} else {
go models.HookQueue.Add(rel.Repo.ID)
}
return err
}

View file

@ -2,27 +2,33 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package models package release
import ( import (
"path/filepath"
"testing" "testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestRelease_Create(t *testing.T) { func TestMain(m *testing.M) {
assert.NoError(t, PrepareTestDatabase()) models.MainTest(m, filepath.Join("..", ".."))
}
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) func TestRelease_Create(t *testing.T) {
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.NoError(t, models.PrepareTestDatabase())
repoPath := RepoPath(user.Name, repo.Name)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoPath := models.RepoPath(user.Name, repo.Name)
gitRepo, err := git.OpenRepository(repoPath) gitRepo, err := git.OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1", TagName: "v0.1",
@ -34,7 +40,7 @@ func TestRelease_Create(t *testing.T) {
IsTag: false, IsTag: false,
}, nil)) }, nil))
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1.1", TagName: "v0.1.1",
@ -46,7 +52,7 @@ func TestRelease_Create(t *testing.T) {
IsTag: false, IsTag: false,
}, nil)) }, nil))
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1.2", TagName: "v0.1.2",
@ -58,7 +64,7 @@ func TestRelease_Create(t *testing.T) {
IsTag: false, IsTag: false,
}, nil)) }, nil))
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1.3", TagName: "v0.1.3",
@ -70,7 +76,7 @@ func TestRelease_Create(t *testing.T) {
IsTag: false, IsTag: false,
}, nil)) }, nil))
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1.4", TagName: "v0.1.4",
@ -82,7 +88,7 @@ func TestRelease_Create(t *testing.T) {
IsTag: false, IsTag: false,
}, nil)) }, nil))
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.1.5", TagName: "v0.1.5",
@ -96,12 +102,12 @@ func TestRelease_Create(t *testing.T) {
} }
func TestRelease_MirrorDelete(t *testing.T) { func TestRelease_MirrorDelete(t *testing.T) {
assert.NoError(t, PrepareTestDatabase()) assert.NoError(t, models.PrepareTestDatabase())
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoPath := RepoPath(user.Name, repo.Name) repoPath := models.RepoPath(user.Name, repo.Name)
migrationOptions := MigrateRepoOptions{ migrationOptions := models.MigrateRepoOptions{
Name: "test_mirror", Name: "test_mirror",
Description: "Test mirror", Description: "Test mirror",
IsPrivate: false, IsPrivate: false,
@ -110,17 +116,17 @@ func TestRelease_MirrorDelete(t *testing.T) {
Wiki: true, Wiki: true,
SyncReleasesWithTags: true, SyncReleasesWithTags: true,
} }
mirror, err := MigrateRepository(user, user, migrationOptions) mirror, err := models.MigrateRepository(user, user, migrationOptions)
assert.NoError(t, err) assert.NoError(t, err)
gitRepo, err := git.OpenRepository(repoPath) gitRepo, err := git.OpenRepository(repoPath)
assert.NoError(t, err) assert.NoError(t, err)
findOptions := FindReleasesOptions{IncludeDrafts: true, IncludeTags: true} findOptions := models.FindReleasesOptions{IncludeDrafts: true, IncludeTags: true}
initCount, err := GetReleaseCountByRepoID(mirror.ID, findOptions) initCount, err := models.GetReleaseCountByRepoID(mirror.ID, findOptions)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, CreateRelease(gitRepo, &Release{ assert.NoError(t, CreateRelease(gitRepo, &models.Release{
RepoID: repo.ID, RepoID: repo.ID,
PublisherID: user.ID, PublisherID: user.ID,
TagName: "v0.2", TagName: "v0.2",
@ -135,21 +141,21 @@ func TestRelease_MirrorDelete(t *testing.T) {
err = mirror.GetMirror() err = mirror.GetMirror()
assert.NoError(t, err) assert.NoError(t, err)
_, ok := mirror.Mirror.runSync() ok := models.RunMirrorSync(mirror.Mirror)
assert.True(t, ok) assert.True(t, ok)
count, err := GetReleaseCountByRepoID(mirror.ID, findOptions) count, err := models.GetReleaseCountByRepoID(mirror.ID, findOptions)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, initCount+1, count) assert.EqualValues(t, initCount+1, count)
release, err := GetRelease(repo.ID, "v0.2") release, err := models.GetRelease(repo.ID, "v0.2")
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, DeleteReleaseByID(release.ID, user, true)) assert.NoError(t, models.DeleteReleaseByID(release.ID, user, true))
_, ok = mirror.Mirror.runSync() ok = models.RunMirrorSync(mirror.Mirror)
assert.True(t, ok) assert.True(t, ok)
count, err = GetReleaseCountByRepoID(mirror.ID, findOptions) count, err = models.GetReleaseCountByRepoID(mirror.ID, findOptions)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, initCount, count) assert.EqualValues(t, initCount, count)
} }