Skip to content

Commit

Permalink
add function to get target branch
Browse files Browse the repository at this point in the history
Refactored the part of the code in runE that determines the target branch
and created a separate function for it.
This will help test the function separately
  • Loading branch information
profclems committed Jan 21, 2021
1 parent aa202ab commit 46d2c0c
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions commands/mr/create/mr_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,7 @@ func NewCmdCreate(f *cmdutils.Factory) *cobra.Command {
}

if opts.TargetBranch == "" {
branchConfig := git.ReadBranchConfig(opts.SourceBranch)
// Check if our given git.BranchConfig{} is not empty, otherwise it will fail
// if try to access the fields, this is needed because the ReadBranchConfig
// function can return an empty struct
if branchConfig != (git.BranchConfig{}) {
if branchConfig.RemoteName != "" && branchConfig.MergeRef != "" {
// The MergeRef takes the form of refs/head/BRANCH_NAME, so split it
// by '/' and get the last element
branchName := strings.Split(branchConfig.MergeRef, "/")
opts.TargetBranch = branchName[len(branchName)-1]
}
} else {
opts.TargetBranch, _ = git.GetDefaultBranch(baseRepoRemote.PushURL.String())
}
opts.TargetBranch = getTargetBranch(baseRepoRemote, opts.SourceBranch)
}

opts.TargetTrackingBranch = fmt.Sprintf("%s/%s", baseRepoRemote.Name, opts.TargetBranch)
Expand Down Expand Up @@ -668,3 +655,22 @@ func repoRemote(labClient *gitlab.Client, opts *CreateOpts, repo glrepo.Interfac

return repoRemote, nil
}

func getTargetBranch(baseRepoRemote *glrepo.Remote, sourceBranch string) string {
branchConfig := git.ReadBranchConfig(sourceBranch)
// Check if our given git.BranchConfig{} is not empty, otherwise it will fail
// if try to access the fields, this is needed because the ReadBranchConfig
// function can return an empty struct
if branchConfig != (git.BranchConfig{}) {
if branchConfig.RemoteName != "" && branchConfig.MergeRef != "" {
// The MergeRef takes the form of refs/head/BRANCH_NAME, so split it
// by '/' and get the last element
branchName := strings.Split(branchConfig.MergeRef, "/")
return branchName[len(branchName)-1]
}
}
br, _ := git.GetDefaultBranch(baseRepoRemote.PushURL.String())
// we ignore the error since git.GetDefaultBranch returns master and an error
// if the default branch cannot be determined
return br
}

0 comments on commit 46d2c0c

Please sign in to comment.