55 "net/http"
66
77 "github.com/cli/cli/api"
8+ "github.com/cli/cli/git"
89 "github.com/cli/cli/internal/config"
910 "github.com/cli/cli/internal/ghrepo"
1011 "github.com/cli/cli/pkg/cmd/pr/shared"
@@ -19,15 +20,19 @@ type CloseOptions struct {
1920 Config func () (config.Config , error )
2021 IO * iostreams.IOStreams
2122 BaseRepo func () (ghrepo.Interface , error )
23+ Branch func () (string , error )
2224
23- SelectorArg string
25+ SelectorArg string
26+ DeleteBranch bool
27+ DeleteLocalBranch bool
2428}
2529
2630func NewCmdClose (f * cmdutil.Factory , runF func (* CloseOptions ) error ) * cobra.Command {
2731 opts := & CloseOptions {
2832 IO : f .IOStreams ,
2933 HttpClient : f .HttpClient ,
3034 Config : f .Config ,
35+ Branch : f .Branch ,
3136 }
3237
3338 cmd := & cobra.Command {
@@ -42,12 +47,15 @@ func NewCmdClose(f *cmdutil.Factory, runF func(*CloseOptions) error) *cobra.Comm
4247 opts .SelectorArg = args [0 ]
4348 }
4449
50+ opts .DeleteLocalBranch = ! cmd .Flags ().Changed ("repo" )
51+
4552 if runF != nil {
4653 return runF (opts )
4754 }
4855 return closeRun (opts )
4956 },
5057 }
58+ cmd .Flags ().BoolVarP (& opts .DeleteBranch , "delete-branch" , "d" , false , "Delete the local and remote branch after close" )
5159
5260 return cmd
5361}
@@ -79,5 +87,52 @@ func closeRun(opts *CloseOptions) error {
7987
8088 fmt .Fprintf (opts .IO .ErrOut , "%s Closed pull request #%d (%s)\n " , utils .Red ("✔" ), pr .Number , pr .Title )
8189
90+ crossRepoPR := pr .HeadRepositoryOwner .Login != baseRepo .RepoOwner ()
91+
92+ if opts .DeleteBranch {
93+ branchSwitchString := ""
94+
95+ if opts .DeleteLocalBranch && ! crossRepoPR {
96+ currentBranch , err := opts .Branch ()
97+ if err != nil {
98+ return err
99+ }
100+
101+ var branchToSwitchTo string
102+ if currentBranch == pr .HeadRefName {
103+ branchToSwitchTo , err = api .RepoDefaultBranch (apiClient , baseRepo )
104+ if err != nil {
105+ return err
106+ }
107+ err = git .CheckoutBranch (branchToSwitchTo )
108+ if err != nil {
109+ return err
110+ }
111+ }
112+
113+ localBranchExists := git .HasLocalBranch (pr .HeadRefName )
114+ if localBranchExists {
115+ err = git .DeleteLocalBranch (pr .HeadRefName )
116+ if err != nil {
117+ err = fmt .Errorf ("failed to delete local branch %s: %w" , utils .Cyan (pr .HeadRefName ), err )
118+ return err
119+ }
120+ }
121+
122+ if branchToSwitchTo != "" {
123+ branchSwitchString = fmt .Sprintf (" and switched to branch %s" , utils .Cyan (branchToSwitchTo ))
124+ }
125+ }
126+
127+ if ! crossRepoPR {
128+ err = api .BranchDeleteRemote (apiClient , baseRepo , pr .HeadRefName )
129+ if err != nil {
130+ err = fmt .Errorf ("failed to delete remote branch %s: %w" , utils .Cyan (pr .HeadRefName ), err )
131+ return err
132+ }
133+ }
134+ fmt .Fprintf (opts .IO .ErrOut , "%s Deleted branch %s%s\n " , utils .Red ("✔" ), utils .Cyan (pr .HeadRefName ), branchSwitchString )
135+ }
136+
82137 return nil
83138}
0 commit comments