Skip to content

Refactor Branch struct in package modules/git #33980

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions models/fixtures/branch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,63 @@
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

-
id: 16
repo_id: 16
name: 'master'
commit_id: '69554a64c1e6030f051e5c3f94bfbd773cd6a324'
commit_message: 'not signed commit'
commit_time: 1502042309
pusher_id: 2
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

-
id: 17
repo_id: 16
name: 'not-signed'
commit_id: '69554a64c1e6030f051e5c3f94bfbd773cd6a324'
commit_message: 'not signed commit'
commit_time: 1502042309
pusher_id: 2
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

-
id: 18
repo_id: 16
name: 'good-sign-not-yet-validated'
commit_id: '27566bd5738fc8b4e3fef3c5e72cce608537bd95'
commit_message: 'good signed commit (with not yet validated email)'
commit_time: 1502042234
pusher_id: 2
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

-
id: 19
repo_id: 16
name: 'good-sign'
commit_id: 'f27c2b2b03dcab38beaf89b0ab4ff61f6de63441'
commit_message: 'good signed commit'
commit_time: 1502042101
pusher_id: 2
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

-
id: 20
repo_id: 1
name: 'feature/1'
commit_id: '65f1bf27bc3bf70f64657658635e66094edbcb4d'
commit_message: 'Initial commit'
commit_time: 1489950479
pusher_id: 2
is_deleted: false
deleted_by_id: 0
deleted_unix: 0
12 changes: 12 additions & 0 deletions models/git/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,18 @@ func GetBranch(ctx context.Context, repoID int64, branchName string) (*Branch, e
return &branch, nil
}

// IsBranchExist returns true if the branch exists in the repository.
func IsBranchExist(ctx context.Context, repoID int64, branchName string) (bool, error) {
var branch Branch
has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
if err != nil {
return false, err
} else if !has {
return false, nil
}
return !branch.IsDeleted, nil
}

func GetBranches(ctx context.Context, repoID int64, branchNames []string, includeDeleted bool) ([]*Branch, error) {
branches := make([]*Branch, 0, len(branchNames))

Expand Down
56 changes: 8 additions & 48 deletions modules/git/repo_branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,34 +25,22 @@ func IsBranchExist(ctx context.Context, repoPath, name string) bool {
return IsReferenceExist(ctx, repoPath, BranchPrefix+name)
}

// Branch represents a Git branch.
type Branch struct {
Name string
Path string

gitRepo *Repository
}

// GetHEADBranch returns corresponding branch of HEAD.
func (repo *Repository) GetHEADBranch() (*Branch, error) {
func (repo *Repository) GetHEADBranch() (string, error) {
if repo == nil {
return nil, fmt.Errorf("nil repo")
return "", fmt.Errorf("nil repo")
}
stdout, _, err := NewCommand("symbolic-ref", "HEAD").RunStdString(repo.Ctx, &RunOpts{Dir: repo.Path})
if err != nil {
return nil, err
return "", err
}
stdout = strings.TrimSpace(stdout)

if !strings.HasPrefix(stdout, BranchPrefix) {
return nil, fmt.Errorf("invalid HEAD branch: %v", stdout)
return "", fmt.Errorf("invalid HEAD branch: %v", stdout)
}

return &Branch{
Name: stdout[len(BranchPrefix):],
Path: stdout,
gitRepo: repo,
}, nil
return stdout[len(BranchPrefix):], nil
}

func GetDefaultBranch(ctx context.Context, repoPath string) (string, error) {
Expand All @@ -68,34 +56,11 @@ func GetDefaultBranch(ctx context.Context, repoPath string) (string, error) {
}

// GetBranch returns a branch by it's name
func (repo *Repository) GetBranch(branch string) (*Branch, error) {
func (repo *Repository) GetBranch(branch string) (string, error) {
if !repo.IsBranchExist(branch) {
return nil, ErrBranchNotExist{branch}
return "", ErrBranchNotExist{branch}
}
return &Branch{
Path: repo.Path,
Name: branch,
gitRepo: repo,
}, nil
}

// GetBranches returns a slice of *git.Branch
func (repo *Repository) GetBranches(skip, limit int) ([]*Branch, int, error) {
brs, countAll, err := repo.GetBranchNames(skip, limit)
if err != nil {
return nil, 0, err
}

branches := make([]*Branch, len(brs))
for i := range brs {
branches[i] = &Branch{
Path: repo.Path,
Name: brs[i],
gitRepo: repo,
}
}

return branches, countAll, nil
return branch, nil
}

// DeleteBranchOptions Option(s) for delete branch
Expand Down Expand Up @@ -147,11 +112,6 @@ func (repo *Repository) RemoveRemote(name string) error {
return err
}

// GetCommit returns the head commit of a branch
func (branch *Branch) GetCommit() (*Commit, error) {
return branch.gitRepo.GetBranchCommit(branch.Name)
}

// RenameBranch rename a branch
func (repo *Repository) RenameBranch(from, to string) error {
_, _, err := NewCommand("branch", "-m").AddDynamicArguments(from, to).RunStdString(repo.Ctx, &RunOpts{Dir: repo.Path})
Expand Down
4 changes: 2 additions & 2 deletions modules/gitrepo/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import (

// GetBranchesByPath returns a branch by its path
// if limit = 0 it will not limit
func GetBranchesByPath(ctx context.Context, repo Repository, skip, limit int) ([]*git.Branch, int, error) {
func GetBranchesByPath(ctx context.Context, repo Repository, skip, limit int) ([]string, int, error) {
gitRepo, err := OpenRepository(ctx, repo)
if err != nil {
return nil, 0, err
}
defer gitRepo.Close()

return gitRepo.GetBranches(skip, limit)
return gitRepo.GetBranchNames(skip, limit)
}

func GetBranchCommitID(ctx context.Context, repo Repository, branch string) (string, error) {
Expand Down
27 changes: 10 additions & 17 deletions routers/api/v1/repo/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,16 @@ func GetBranch(ctx *context.APIContext) {

branchName := ctx.PathParam("*")

branch, err := ctx.Repo.GitRepo.GetBranch(branchName)
exist, err := git_model.IsBranchExist(ctx, ctx.Repo.Repository.ID, branchName)
if err != nil {
if git.IsErrBranchNotExist(err) {
ctx.APIErrorNotFound(err)
} else {
ctx.APIErrorInternal(err)
}
ctx.APIErrorInternal(err)
return
} else if !exist {
ctx.APIErrorNotFound(err)
return
}

c, err := branch.GetCommit()
c, err := ctx.Repo.GitRepo.GetBranchCommit(branchName)
if err != nil {
ctx.APIErrorInternal(err)
return
Expand All @@ -82,7 +81,7 @@ func GetBranch(ctx *context.APIContext) {
return
}

br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch.Name, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branchName, c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
if err != nil {
ctx.APIErrorInternal(err)
return
Expand Down Expand Up @@ -261,25 +260,19 @@ func CreateBranch(ctx *context.APIContext) {
return
}

branch, err := ctx.Repo.GitRepo.GetBranch(opt.BranchName)
if err != nil {
ctx.APIErrorInternal(err)
return
}

commit, err := branch.GetCommit()
commit, err := ctx.Repo.GitRepo.GetBranchCommit(opt.BranchName)
if err != nil {
ctx.APIErrorInternal(err)
return
}

branchProtection, err := git_model.GetFirstMatchProtectedBranchRule(ctx, ctx.Repo.Repository.ID, branch.Name)
branchProtection, err := git_model.GetFirstMatchProtectedBranchRule(ctx, ctx.Repo.Repository.ID, opt.BranchName)
if err != nil {
ctx.APIErrorInternal(err)
return
}

br, err := convert.ToBranch(ctx, ctx.Repo.Repository, branch.Name, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
br, err := convert.ToBranch(ctx, ctx.Repo.Repository, opt.BranchName, commit, branchProtection, ctx.Doer, ctx.Repo.IsAdmin())
if err != nil {
ctx.APIErrorInternal(err)
return
Expand Down
2 changes: 1 addition & 1 deletion routers/api/v1/repo/commits.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func GetAllCommits(ctx *context.APIContext) {
return
}

baseCommit, err = ctx.Repo.GitRepo.GetBranchCommit(head.Name)
baseCommit, err = ctx.Repo.GitRepo.GetBranchCommit(head)
if err != nil {
ctx.APIErrorInternal(err)
return
Expand Down
2 changes: 1 addition & 1 deletion routers/web/repo/view_home.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ func handleRepoEmptyOrBroken(ctx *context.Context) {
} else if reallyEmpty {
showEmpty = true // the repo is really empty
updateContextRepoEmptyAndStatus(ctx, true, repo_model.RepositoryReady)
} else if branches, _, _ := ctx.Repo.GitRepo.GetBranches(0, 1); len(branches) == 0 {
} else if branches, _, _ := ctx.Repo.GitRepo.GetBranchNames(0, 1); len(branches) == 0 {
showEmpty = true // it is not really empty, but there is no branch
// at the moment, other repo units like "actions" are not able to handle such case,
// so we just mark the repo as empty to prevent from displaying these units.
Expand Down
4 changes: 2 additions & 2 deletions services/context/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -815,9 +815,9 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) {
if reqPath == "" {
refShortName = ctx.Repo.Repository.DefaultBranch
if !gitrepo.IsBranchExist(ctx, ctx.Repo.Repository, refShortName) {
brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 1)
brs, _, err := ctx.Repo.GitRepo.GetBranchNames(0, 1)
if err == nil && len(brs) != 0 {
refShortName = brs[0].Name
refShortName = brs[0]
} else if len(brs) == 0 {
log.Error("No branches in non-empty repository %s", ctx.Repo.GitRepo.Path)
} else {
Expand Down
23 changes: 8 additions & 15 deletions services/convert/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import (
// Optional - Merger
func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User) *api.PullRequest {
var (
baseBranch *git.Branch
headBranch *git.Branch
baseBranch string
headBranch string
baseCommit *git.Commit
err error
)
Expand Down Expand Up @@ -157,9 +157,9 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
}

if err == nil {
baseCommit, err = baseBranch.GetCommit()
baseCommit, err = gitRepo.GetBranchCommit(pr.BaseBranch)
if err != nil && !git.IsErrNotExist(err) {
log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
log.Error("GetCommit[%s]: %v", baseBranch, err)
return nil
}

Expand All @@ -169,13 +169,6 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
}

if pr.Flow == issues_model.PullRequestFlowAGit {
gitRepo, err := gitrepo.OpenRepository(ctx, pr.BaseRepo)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 146 has created gitRepo.

if err != nil {
log.Error("OpenRepository[%s]: %v", pr.GetGitRefName(), err)
return nil
}
defer gitRepo.Close()

apiPullRequest.Head.Sha, err = gitRepo.GetRefCommitID(pr.GetGitRefName())
if err != nil {
log.Error("GetRefCommitID[%s]: %v", pr.GetGitRefName(), err)
Expand Down Expand Up @@ -226,9 +219,9 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u
endCommitID = headCommitID
}
} else {
commit, err := headBranch.GetCommit()
commit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
if err != nil && !git.IsErrNotExist(err) {
log.Error("GetCommit[%s]: %v", headBranch.Name, err)
log.Error("GetCommit[%s]: %v", headBranch, err)
return nil
}
if err == nil {
Expand Down Expand Up @@ -478,9 +471,9 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs
apiPullRequest.Head.Sha = headCommitID
}
} else {
commit, err := headBranch.GetCommit()
commit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
if err != nil && !git.IsErrNotExist(err) {
log.Error("GetCommit[%s]: %v", headBranch.Name, err)
log.Error("GetCommit[%s]: %v", headBranch, err)
return nil, err
}
if err == nil {
Expand Down
2 changes: 1 addition & 1 deletion services/mirror/mirror_pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo
}

for _, branch := range branches {
cache.Remove(m.Repo.GetCommitsCountCacheKey(branch.Name, true))
cache.Remove(m.Repo.GetCommitsCountCacheKey(branch, true))
}

m.UpdatedUnix = timeutil.TimeStampNow()
Expand Down
2 changes: 1 addition & 1 deletion services/pull/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func CloseRepoBranchesPulls(ctx context.Context, doer *user_model.User, repo *re

var errs []error
for _, branch := range branches {
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(ctx, repo.ID, branch.Name)
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(ctx, repo.ID, branch)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion services/repository/files/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (opts *ApplyDiffPatchOptions) Validate(ctx context.Context, repo *repo_mode
// 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 := gitRepo.GetBranch(opts.NewBranch)
if existingBranch != nil {
if existingBranch != "" {
return git_model.ErrBranchAlreadyExists{
BranchName: opts.NewBranch,
}
Expand Down
2 changes: 1 addition & 1 deletion services/repository/files/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func ChangeRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use
// 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 := gitRepo.GetBranch(opts.NewBranch)
if existingBranch != nil {
if existingBranch != "" {
return nil, git_model.ErrBranchAlreadyExists{
BranchName: opts.NewBranch,
}
Expand Down
4 changes: 2 additions & 2 deletions services/repository/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
if err != nil {
return repo, fmt.Errorf("GetHEADBranch: %w", err)
}
if headBranch != nil {
repo.DefaultBranch = headBranch.Name
if headBranch != "" {
repo.DefaultBranch = headBranch
}
}

Expand Down
Loading