github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/pr/reopen/reopen.go (about) 1 package reopen 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/ungtb10d/cli/v2/api" 8 "github.com/ungtb10d/cli/v2/internal/ghrepo" 9 "github.com/ungtb10d/cli/v2/pkg/cmd/pr/shared" 10 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 11 "github.com/ungtb10d/cli/v2/pkg/iostreams" 12 "github.com/spf13/cobra" 13 ) 14 15 type ReopenOptions struct { 16 HttpClient func() (*http.Client, error) 17 IO *iostreams.IOStreams 18 19 Finder shared.PRFinder 20 21 SelectorArg string 22 Comment string 23 } 24 25 func NewCmdReopen(f *cmdutil.Factory, runF func(*ReopenOptions) error) *cobra.Command { 26 opts := &ReopenOptions{ 27 IO: f.IOStreams, 28 HttpClient: f.HttpClient, 29 } 30 31 cmd := &cobra.Command{ 32 Use: "reopen {<number> | <url> | <branch>}", 33 Short: "Reopen a pull request", 34 Args: cobra.ExactArgs(1), 35 RunE: func(cmd *cobra.Command, args []string) error { 36 opts.Finder = shared.NewFinder(f) 37 38 if len(args) > 0 { 39 opts.SelectorArg = args[0] 40 } 41 42 if runF != nil { 43 return runF(opts) 44 } 45 return reopenRun(opts) 46 }, 47 } 48 49 cmd.Flags().StringVarP(&opts.Comment, "comment", "c", "", "Add a reopening comment") 50 51 return cmd 52 } 53 54 func reopenRun(opts *ReopenOptions) error { 55 cs := opts.IO.ColorScheme() 56 57 findOptions := shared.FindOptions{ 58 Selector: opts.SelectorArg, 59 Fields: []string{"id", "number", "state", "title"}, 60 } 61 pr, baseRepo, err := opts.Finder.Find(findOptions) 62 if err != nil { 63 return err 64 } 65 66 if pr.State == "MERGED" { 67 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) 68 return cmdutil.SilentError 69 } 70 71 if pr.IsOpen() { 72 fmt.Fprintf(opts.IO.ErrOut, "%s Pull request #%d (%s) is already open\n", cs.WarningIcon(), pr.Number, pr.Title) 73 return nil 74 } 75 76 httpClient, err := opts.HttpClient() 77 if err != nil { 78 return err 79 } 80 81 if opts.Comment != "" { 82 commentOpts := &shared.CommentableOptions{ 83 Body: opts.Comment, 84 HttpClient: opts.HttpClient, 85 InputType: shared.InputTypeInline, 86 Quiet: true, 87 RetrieveCommentable: func() (shared.Commentable, ghrepo.Interface, error) { 88 return pr, baseRepo, nil 89 }, 90 } 91 err := shared.CommentableRun(commentOpts) 92 if err != nil { 93 return err 94 } 95 } 96 97 err = api.PullRequestReopen(httpClient, baseRepo, pr.ID) 98 if err != nil { 99 return fmt.Errorf("API call failed: %w", err) 100 } 101 102 fmt.Fprintf(opts.IO.ErrOut, "%s Reopened pull request #%d (%s)\n", cs.SuccessIconWithColor(cs.Green), pr.Number, pr.Title) 103 104 return nil 105 }