github.com/andrewhsu/cli/v2@v2.0.1-0.20210910131313-d4b4061f5b89/pkg/cmd/pr/reopen/reopen.go (about)

     1  package reopen
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/andrewhsu/cli/v2/api"
     8  	"github.com/andrewhsu/cli/v2/pkg/cmd/pr/shared"
     9  	"github.com/andrewhsu/cli/v2/pkg/cmdutil"
    10  	"github.com/andrewhsu/cli/v2/pkg/iostreams"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type ReopenOptions struct {
    15  	HttpClient func() (*http.Client, error)
    16  	IO         *iostreams.IOStreams
    17  
    18  	Finder shared.PRFinder
    19  
    20  	SelectorArg string
    21  }
    22  
    23  func NewCmdReopen(f *cmdutil.Factory, runF func(*ReopenOptions) error) *cobra.Command {
    24  	opts := &ReopenOptions{
    25  		IO:         f.IOStreams,
    26  		HttpClient: f.HttpClient,
    27  	}
    28  
    29  	cmd := &cobra.Command{
    30  		Use:   "reopen {<number> | <url> | <branch>}",
    31  		Short: "Reopen a pull request",
    32  		Args:  cobra.ExactArgs(1),
    33  		RunE: func(cmd *cobra.Command, args []string) error {
    34  			opts.Finder = shared.NewFinder(f)
    35  
    36  			if len(args) > 0 {
    37  				opts.SelectorArg = args[0]
    38  			}
    39  
    40  			if runF != nil {
    41  				return runF(opts)
    42  			}
    43  			return reopenRun(opts)
    44  		},
    45  	}
    46  
    47  	return cmd
    48  }
    49  
    50  func reopenRun(opts *ReopenOptions) error {
    51  	cs := opts.IO.ColorScheme()
    52  
    53  	findOptions := shared.FindOptions{
    54  		Selector: opts.SelectorArg,
    55  		Fields:   []string{"id", "number", "state", "title"},
    56  	}
    57  	pr, baseRepo, err := opts.Finder.Find(findOptions)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	if pr.State == "MERGED" {
    63  		fmt.Fprintf(opts.IO.ErrOut, "%s Pull request #%d (%s) can't be reopened because it was already merged\n", cs.FailureIcon(), pr.Number, pr.Title)
    64  		return cmdutil.SilentError
    65  	}
    66  
    67  	if pr.IsOpen() {
    68  		fmt.Fprintf(opts.IO.ErrOut, "%s Pull request #%d (%s) is already open\n", cs.WarningIcon(), pr.Number, pr.Title)
    69  		return nil
    70  	}
    71  
    72  	httpClient, err := opts.HttpClient()
    73  	if err != nil {
    74  		return err
    75  	}
    76  	apiClient := api.NewClientFromHTTP(httpClient)
    77  
    78  	err = api.PullRequestReopen(apiClient, baseRepo, pr)
    79  	if err != nil {
    80  		return fmt.Errorf("API call failed: %w", err)
    81  	}
    82  
    83  	fmt.Fprintf(opts.IO.ErrOut, "%s Reopened pull request #%d (%s)\n", cs.SuccessIconWithColor(cs.Green), pr.Number, pr.Title)
    84  
    85  	return nil
    86  }