github.com/emmahsax/go-git-helper@v0.0.8-0.20240519163017-907b9de0fa52/cmd/newBranch/newBranch.go (about)

     1  package newBranch
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/emmahsax/go-git-helper/internal/commandline"
     7  	"github.com/emmahsax/go-git-helper/internal/executor"
     8  	"github.com/emmahsax/go-git-helper/internal/git"
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  type NewBranch struct {
    13  	Branch   string
    14  	Debug    bool
    15  	Executor executor.ExecutorInterface
    16  }
    17  
    18  func NewCommand() *cobra.Command {
    19  	var (
    20  		debug bool
    21  	)
    22  
    23  	cmd := &cobra.Command{
    24  		Use:                   "new-branch [optionalBranch]",
    25  		Short:                 "Creates a new local branch and pushes to the remote",
    26  		Args:                  cobra.MaximumNArgs(1),
    27  		DisableFlagsInUseLine: true,
    28  		RunE: func(cmd *cobra.Command, args []string) error {
    29  			newNewBranch(determineBranch(args), debug, executor.NewExecutor(debug)).execute()
    30  			return nil
    31  		},
    32  	}
    33  
    34  	cmd.Flags().BoolVar(&debug, "debug", false, "enables debug mode")
    35  
    36  	return cmd
    37  }
    38  
    39  func newNewBranch(branch string, debug bool, executor executor.ExecutorInterface) *NewBranch {
    40  	return &NewBranch{
    41  		Branch:   branch,
    42  		Debug:    debug,
    43  		Executor: executor,
    44  	}
    45  }
    46  
    47  func determineBranch(args []string) string {
    48  	if len(args) == 0 {
    49  		return askForBranch()
    50  	} else {
    51  		return args[0]
    52  	}
    53  }
    54  
    55  func askForBranch() string {
    56  	return commandline.AskOpenEndedQuestion("New branch name", false)
    57  }
    58  
    59  func (nb *NewBranch) execute() {
    60  	fmt.Println("Attempting to create a new branch:", nb.Branch)
    61  	g := git.NewGit(nb.Debug, nb.Executor)
    62  	g.Pull()
    63  
    64  	for {
    65  		err := g.CreateBranch(nb.Branch)
    66  		if err == nil {
    67  			break
    68  		}
    69  
    70  		fmt.Println("--- Invalid branch ---")
    71  		nb.Branch = askForBranch()
    72  	}
    73  
    74  	g.Checkout(nb.Branch)
    75  	g.PushBranch(nb.Branch)
    76  }