1
0
mirror of https://github.com/go-gitea/gitea.git synced 2024-12-22 17:34:03 +03:00

Move newbranch to standalone package (#9627)

* Move newbranch to standalone package

* move branch functions to modules to avoid dependencies cycles

* fix tests

* fix lint

* fix lint
This commit is contained in:
Lunny Xiao 2020-01-14 11:38:04 +08:00 committed by GitHub
parent bca367cecc
commit 2677d071f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 208 additions and 183 deletions

View File

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -71,15 +72,18 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
// Make a new branch in repo1
newBranch := "test_branch"
repo1.CreateNewBranch(user2, repo1.DefaultBranch, newBranch)
err := repo_module.CreateNewBranch(user2, repo1, repo1.DefaultBranch, newBranch)
assert.NoError(t, err)
// Get the commit ID of the default branch
gitRepo, _ := git.OpenRepository(repo1.RepoPath())
gitRepo, err := git.OpenRepository(repo1.RepoPath())
assert.NoError(t, err)
defer gitRepo.Close()
commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch)
// Make a new tag in repo1
newTag := "test_tag"
gitRepo.CreateTag(newTag, commitID)
err = gitRepo.CreateTag(newTag, commitID)
assert.NoError(t, err)
/*** END SETUP ***/
// ref is default ref

View File

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -72,15 +73,19 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
// Make a new branch in repo1
newBranch := "test_branch"
repo1.CreateNewBranch(user2, repo1.DefaultBranch, newBranch)
err := repo_module.CreateNewBranch(user2, repo1, repo1.DefaultBranch, newBranch)
assert.NoError(t, err)
// Get the commit ID of the default branch
gitRepo, _ := git.OpenRepository(repo1.RepoPath())
gitRepo, err := git.OpenRepository(repo1.RepoPath())
assert.NoError(t, err)
defer gitRepo.Close()
commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch)
commitID, err := gitRepo.GetBranchCommitID(repo1.DefaultBranch)
assert.NoError(t, err)
// Make a new tag in repo1
newTag := "test_tag"
gitRepo.CreateTag(newTag, commitID)
err = gitRepo.CreateTag(newTag, commitID)
assert.NoError(t, err)
/*** END SETUP ***/
// ref is default ref

View File

@ -5,158 +5,7 @@
package models
import (
"fmt"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
)
// CanCreateBranch returns true if repository meets the requirements for creating new branches.
func (repo *Repository) CanCreateBranch() bool {
return !repo.IsMirror
}
// GetBranch returns a branch by its name
func (repo *Repository) GetBranch(branch string) (*git.Branch, error) {
gitRepo, err := git.OpenRepository(repo.RepoPath())
if err != nil {
return nil, err
}
defer gitRepo.Close()
return gitRepo.GetBranch(branch)
}
// GetBranches returns all the branches of a repository
func (repo *Repository) GetBranches() ([]*git.Branch, error) {
return git.GetBranchesByPath(repo.RepoPath())
}
// CheckBranchName validates branch name with existing repository branches
func (repo *Repository) CheckBranchName(name string) error {
gitRepo, err := git.OpenRepository(repo.RepoPath())
if err != nil {
return err
}
defer gitRepo.Close()
branches, err := repo.GetBranches()
if err != nil {
return err
}
for _, branch := range branches {
if branch.Name == name {
return ErrBranchAlreadyExists{branch.Name}
} else if (len(branch.Name) < len(name) && branch.Name+"/" == name[0:len(branch.Name)+1]) ||
(len(branch.Name) > len(name) && name+"/" == branch.Name[0:len(name)+1]) {
return ErrBranchNameConflict{branch.Name}
}
}
if _, err := gitRepo.GetTag(name); err == nil {
return ErrTagAlreadyExists{name}
}
return nil
}
// CreateNewBranch creates a new repository branch
func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) {
// Check if branch name can be used
if err := repo.CheckBranchName(branchName); err != nil {
return err
}
if !git.IsBranchExist(repo.RepoPath(), oldBranchName) {
return fmt.Errorf("OldBranch: %s does not exist. Cannot create new branch from this", oldBranchName)
}
basePath, err := CreateTemporaryPath("branch-maker")
if err != nil {
return err
}
defer func() {
if err := RemoveTemporaryPath(basePath); err != nil {
log.Error("CreateNewBranch: RemoveTemporaryPath: %s", err)
}
}()
if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{
Bare: true,
Shared: true,
}); err != nil {
log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
return fmt.Errorf("Failed to clone repository: %s (%v)", repo.FullName(), err)
}
gitRepo, err := git.OpenRepository(basePath)
if err != nil {
log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
}
defer gitRepo.Close()
if err = gitRepo.CreateBranch(branchName, oldBranchName); err != nil {
log.Error("Unable to create branch: %s from %s. (%v)", branchName, oldBranchName, err)
return fmt.Errorf("Unable to create branch: %s from %s. (%v)", branchName, oldBranchName, err)
}
if err = git.Push(basePath, git.PushOptions{
Remote: "origin",
Branch: branchName,
Env: PushingEnvironment(doer, repo),
}); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}
// CreateNewBranchFromCommit creates a new repository branch
func (repo *Repository) CreateNewBranchFromCommit(doer *User, commit, branchName string) (err error) {
// Check if branch name can be used
if err := repo.CheckBranchName(branchName); err != nil {
return err
}
basePath, err := CreateTemporaryPath("branch-maker")
if err != nil {
return err
}
defer func() {
if err := RemoveTemporaryPath(basePath); err != nil {
log.Error("CreateNewBranchFromCommit: RemoveTemporaryPath: %s", err)
}
}()
if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{
Bare: true,
Shared: true,
}); err != nil {
log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
return fmt.Errorf("Failed to clone repository: %s (%v)", repo.FullName(), err)
}
gitRepo, err := git.OpenRepository(basePath)
if err != nil {
log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
}
defer gitRepo.Close()
if err = gitRepo.CreateBranch(branchName, commit); err != nil {
log.Error("Unable to create branch: %s from %s. (%v)", branchName, commit, err)
return fmt.Errorf("Unable to create branch: %s from %s. (%v)", branchName, commit, err)
}
if err = git.Push(basePath, git.PushOptions{
Remote: "origin",
Branch: branchName,
Env: PushingEnvironment(doer, repo),
}); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}

View File

@ -8,6 +8,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
repo_module "code.gitea.io/gitea/modules/repository"
api "code.gitea.io/gitea/modules/structs"
)
@ -69,7 +70,7 @@ func ToAPIPullRequest(pr *models.PullRequest) *api.PullRequest {
Created: pr.Issue.CreatedUnix.AsTimePtr(),
Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
}
baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
baseBranch, err = repo_module.GetBranch(pr.BaseRepo, pr.BaseBranch)
if err != nil {
if git.IsErrBranchNotExist(err) {
apiPullRequest.Base = nil
@ -98,7 +99,7 @@ func ToAPIPullRequest(pr *models.PullRequest) *api.PullRequest {
apiPullRequest.Base = apiBaseBranchInfo
}
headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
headBranch, err = repo_module.GetBranch(pr.HeadRepo, pr.HeadBranch)
if err != nil {
if git.IsErrBranchNotExist(err) {
apiPullRequest.Head = nil

View File

@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
api "code.gitea.io/gitea/modules/structs"
)
@ -37,7 +38,7 @@ func DeleteRepoFile(repo *models.Repository, doer *models.User, opts *DeleteRepo
}
// oldBranch must exist for this operation
if _, err := repo.GetBranch(opts.OldBranch); err != nil {
if _, err := repo_module.GetBranch(repo, opts.OldBranch); err != nil {
return nil, err
}
@ -45,7 +46,7 @@ func DeleteRepoFile(repo *models.Repository, doer *models.User, opts *DeleteRepo
// Check to make sure the branch does not already exist, otherwise we can't proceed.
// If we aren't branching to a new branch, make sure user can commit to the given branch
if opts.NewBranch != opts.OldBranch {
newBranch, err := repo.GetBranch(opts.NewBranch)
newBranch, err := repo_module.GetBranch(repo, opts.NewBranch)
if git.IsErrNotExist(err) {
return nil, err
}

View File

@ -18,7 +18,7 @@ import (
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/repository"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
pull_service "code.gitea.io/gitea/services/pull"
@ -134,7 +134,7 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *Up
}
// oldBranch must exist for this operation
if _, err := repo.GetBranch(opts.OldBranch); err != nil {
if _, err := repo_module.GetBranch(repo, opts.OldBranch); err != nil {
return nil, err
}
@ -142,7 +142,7 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *Up
// Check to make sure the branch does not already exist, otherwise we can't proceed.
// If we aren't branching to a new branch, make sure user can commit to the given branch
if opts.NewBranch != opts.OldBranch {
existingBranch, err := repo.GetBranch(opts.NewBranch)
existingBranch, err := repo_module.GetBranch(repo, opts.NewBranch)
if existingBranch != nil {
return nil, models.ErrBranchAlreadyExists{
BranchName: opts.NewBranch,
@ -550,7 +550,7 @@ func createCommitRepoActions(repo *models.Repository, gitRepo *git.Repository, o
if isNewRef && isDelRef {
return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
}
var commits = &repository.PushCommits{}
var commits = &repo_module.PushCommits{}
if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
// If is tag reference
tagName := opts.RefFullName[len(git.TagPrefix):]
@ -585,7 +585,7 @@ func createCommitRepoActions(repo *models.Repository, gitRepo *git.Repository, o
}
}
commits = repository.ListToPushCommits(l)
commits = repo_module.ListToPushCommits(l)
}
actions = append(actions, &CommitRepoActionOptions{
PusherName: opts.PusherName,
@ -610,7 +610,7 @@ func createCommitRepoActionOption(repo *models.Repository, gitRepo *git.Reposito
return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
}
var commits = &repository.PushCommits{}
var commits = &repo_module.PushCommits{}
if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
// If is tag reference
tagName := opts.RefFullName[len(git.TagPrefix):]
@ -621,7 +621,7 @@ func createCommitRepoActionOption(repo *models.Repository, gitRepo *git.Reposito
} else {
// Clear cache for tag commit count
cache.Remove(repo.GetCommitsCountCacheKey(tagName, true))
if err := repository.PushUpdateAddTag(repo, gitRepo, tagName); err != nil {
if err := repo_module.PushUpdateAddTag(repo, gitRepo, tagName); err != nil {
return nil, fmt.Errorf("PushUpdateAddTag: %v", err)
}
}
@ -650,7 +650,7 @@ func createCommitRepoActionOption(repo *models.Repository, gitRepo *git.Reposito
}
}
commits = repository.ListToPushCommits(l)
commits = repo_module.ListToPushCommits(l)
}
return &CommitRepoActionOptions{

View File

@ -0,0 +1,163 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package repository
import (
"fmt"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
)
// GetBranch returns a branch by its name
func GetBranch(repo *models.Repository, branch string) (*git.Branch, error) {
gitRepo, err := git.OpenRepository(repo.RepoPath())
if err != nil {
return nil, err
}
defer gitRepo.Close()
return gitRepo.GetBranch(branch)
}
// GetBranches returns all the branches of a repository
func GetBranches(repo *models.Repository) ([]*git.Branch, error) {
return git.GetBranchesByPath(repo.RepoPath())
}
// checkBranchName validates branch name with existing repository branches
func checkBranchName(repo *models.Repository, name string) error {
gitRepo, err := git.OpenRepository(repo.RepoPath())
if err != nil {
return err
}
defer gitRepo.Close()
branches, err := GetBranches(repo)
if err != nil {
return err
}
for _, branch := range branches {
if branch.Name == name {
return models.ErrBranchAlreadyExists{
BranchName: branch.Name,
}
} else if (len(branch.Name) < len(name) && branch.Name+"/" == name[0:len(branch.Name)+1]) ||
(len(branch.Name) > len(name) && name+"/" == branch.Name[0:len(name)+1]) {
return models.ErrBranchNameConflict{
BranchName: branch.Name,
}
}
}
if _, err := gitRepo.GetTag(name); err == nil {
return models.ErrTagAlreadyExists{
TagName: name,
}
}
return nil
}
// CreateNewBranch creates a new repository branch
func CreateNewBranch(doer *models.User, repo *models.Repository, oldBranchName, branchName string) (err error) {
// Check if branch name can be used
if err := checkBranchName(repo, branchName); err != nil {
return err
}
if !git.IsBranchExist(repo.RepoPath(), oldBranchName) {
return fmt.Errorf("OldBranch: %s does not exist. Cannot create new branch from this", oldBranchName)
}
basePath, err := models.CreateTemporaryPath("branch-maker")
if err != nil {
return err
}
defer func() {
if err := models.RemoveTemporaryPath(basePath); err != nil {
log.Error("CreateNewBranch: RemoveTemporaryPath: %s", err)
}
}()
if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{
Bare: true,
Shared: true,
}); err != nil {
log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
return fmt.Errorf("Failed to clone repository: %s (%v)", repo.FullName(), err)
}
gitRepo, err := git.OpenRepository(basePath)
if err != nil {
log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
}
defer gitRepo.Close()
if err = gitRepo.CreateBranch(branchName, oldBranchName); err != nil {
log.Error("Unable to create branch: %s from %s. (%v)", branchName, oldBranchName, err)
return fmt.Errorf("Unable to create branch: %s from %s. (%v)", branchName, oldBranchName, err)
}
if err = git.Push(basePath, git.PushOptions{
Remote: "origin",
Branch: branchName,
Env: models.PushingEnvironment(doer, repo),
}); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}
// CreateNewBranchFromCommit creates a new repository branch
func CreateNewBranchFromCommit(doer *models.User, repo *models.Repository, commit, branchName string) (err error) {
// Check if branch name can be used
if err := checkBranchName(repo, branchName); err != nil {
return err
}
basePath, err := models.CreateTemporaryPath("branch-maker")
if err != nil {
return err
}
defer func() {
if err := models.RemoveTemporaryPath(basePath); err != nil {
log.Error("CreateNewBranchFromCommit: RemoveTemporaryPath: %s", err)
}
}()
if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{
Bare: true,
Shared: true,
}); err != nil {
log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
return fmt.Errorf("Failed to clone repository: %s (%v)", repo.FullName(), err)
}
gitRepo, err := git.OpenRepository(basePath)
if err != nil {
log.Error("Unable to open temporary repository: %s (%v)", basePath, err)
return fmt.Errorf("Failed to open new temporary repository in: %s %v", basePath, err)
}
defer gitRepo.Close()
if err = gitRepo.CreateBranch(branchName, commit); err != nil {
log.Error("Unable to create branch: %s from %s. (%v)", branchName, commit, err)
return fmt.Errorf("Unable to create branch: %s from %s. (%v)", branchName, commit, err)
}
if err = git.Push(basePath, git.PushOptions{
Remote: "origin",
Branch: branchName,
Env: models.PushingEnvironment(doer, repo),
}); err != nil {
return fmt.Errorf("Push: %v", err)
}
return nil
}

View File

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
api "code.gitea.io/gitea/modules/structs"
)
@ -48,7 +49,7 @@ func GetBranch(ctx *context.APIContext) {
ctx.NotFound()
return
}
branch, err := ctx.Repo.Repository.GetBranch(ctx.Repo.BranchName)
branch, err := repo_module.GetBranch(ctx.Repo.Repository, ctx.Repo.BranchName)
if err != nil {
if git.IsErrBranchNotExist(err) {
ctx.NotFound(err)
@ -95,7 +96,7 @@ func ListBranches(ctx *context.APIContext) {
// "200":
// "$ref": "#/responses/BranchList"
branches, err := ctx.Repo.Repository.GetBranches()
branches, err := repo_module.GetBranches(ctx.Repo.Repository)
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetBranches", err)
return

View File

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/repofiles"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/util"
"gopkg.in/src-d/go-git.v4/plumbing"
)
@ -175,7 +176,7 @@ func deleteBranch(ctx *context.Context, branchName string) error {
}
func loadBranches(ctx *context.Context) []*Branch {
rawBranches, err := ctx.Repo.Repository.GetBranches()
rawBranches, err := repo_module.GetBranches(ctx.Repo.Repository)
if err != nil {
ctx.ServerError("GetBranches", err)
return nil
@ -324,9 +325,9 @@ func CreateBranch(ctx *context.Context, form auth.NewBranchForm) {
var err error
if ctx.Repo.IsViewBranch {
err = ctx.Repo.Repository.CreateNewBranch(ctx.User, ctx.Repo.BranchName, form.NewBranchName)
err = repo_module.CreateNewBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
} else {
err = ctx.Repo.Repository.CreateNewBranchFromCommit(ctx.User, ctx.Repo.BranchName, form.NewBranchName)
err = repo_module.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
}
if err != nil {
if models.IsErrTagAlreadyExists(err) {

View File

@ -19,6 +19,7 @@ import (
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/repofiles"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/upload"
"code.gitea.io/gitea/modules/util"
@ -534,7 +535,7 @@ func UploadFilePost(ctx *context.Context, form auth.UploadRepoFileForm) {
}
if oldBranchName != branchName {
if _, err := ctx.Repo.Repository.GetBranch(branchName); err == nil {
if _, err := repo_module.GetBranch(ctx.Repo.Repository, branchName); err == nil {
ctx.Data["Err_NewBranchName"] = true
ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplUploadFile, &form)
return
@ -679,7 +680,7 @@ func GetUniquePatchBranchName(ctx *context.Context) string {
prefix := ctx.User.LowerName + "-patch-"
for i := 1; i <= 1000; i++ {
branchName := fmt.Sprintf("%s%d", prefix, i)
if _, err := ctx.Repo.Repository.GetBranch(branchName); err != nil {
if _, err := repo_module.GetBranch(ctx.Repo.Repository, branchName); err != nil {
if git.IsErrBranchNotExist(err) {
return branchName
}

View File

@ -11,14 +11,13 @@ import (
"strings"
"time"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification"
"code.gitea.io/gitea/modules/repository"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/sync"
"code.gitea.io/gitea/modules/timeutil"
@ -211,7 +210,7 @@ func runSync(m *models.Mirror) ([]*mirrorSyncResult, bool) {
log.Error("OpenRepository: %v", err)
return nil, false
}
if err = repository.SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
if err = repo_module.SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
gitRepo.Close()
log.Error("Failed to synchronize tags to releases for repository: %v", err)
}
@ -253,7 +252,7 @@ func runSync(m *models.Mirror) ([]*mirrorSyncResult, bool) {
}
}
branches, err := m.Repo.GetBranches()
branches, err := repo_module.GetBranches(m.Repo)
if err != nil {
log.Error("GetBranches: %v", err)
return nil, false
@ -403,7 +402,7 @@ func syncMirror(repoID string) {
continue
}
theCommits := repository.ListToPushCommits(commits)
theCommits := repo_module.ListToPushCommits(commits)
if len(theCommits.Commits) > setting.UI.FeedMaxCommitNum {
theCommits.Commits = theCommits.Commits[:setting.UI.FeedMaxCommitNum]
}