github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmd/gist/delete/delete.go (about)

     1  package delete
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/cli/cli/api"
     9  	"github.com/cli/cli/internal/config"
    10  	"github.com/cli/cli/pkg/cmd/gist/shared"
    11  	"github.com/cli/cli/pkg/cmdutil"
    12  	"github.com/cli/cli/pkg/iostreams"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  type DeleteOptions struct {
    17  	IO         *iostreams.IOStreams
    18  	Config     func() (config.Config, error)
    19  	HttpClient func() (*http.Client, error)
    20  
    21  	Selector string
    22  }
    23  
    24  func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
    25  	opts := DeleteOptions{
    26  		IO:         f.IOStreams,
    27  		Config:     f.Config,
    28  		HttpClient: f.HttpClient,
    29  	}
    30  
    31  	cmd := &cobra.Command{
    32  		Use:   "delete {<id> | <url>}",
    33  		Short: "Delete a gist",
    34  		Args:  cmdutil.ExactArgs(1, "cannot delete: gist argument required"),
    35  		RunE: func(c *cobra.Command, args []string) error {
    36  			opts.Selector = args[0]
    37  			if runF != nil {
    38  				return runF(&opts)
    39  			}
    40  			return deleteRun(&opts)
    41  		},
    42  	}
    43  	return cmd
    44  }
    45  
    46  func deleteRun(opts *DeleteOptions) error {
    47  	gistID := opts.Selector
    48  
    49  	if strings.Contains(gistID, "/") {
    50  		id, err := shared.GistIDFromURL(gistID)
    51  		if err != nil {
    52  			return err
    53  		}
    54  		gistID = id
    55  	}
    56  	client, err := opts.HttpClient()
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	apiClient := api.NewClientFromHTTP(client)
    62  
    63  	cfg, err := opts.Config()
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	host, err := cfg.DefaultHost()
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	gist, err := shared.GetGist(client, host, gistID)
    74  	if err != nil {
    75  		return err
    76  	}
    77  	username, err := api.CurrentLoginName(apiClient, host)
    78  	if err != nil {
    79  		return err
    80  	}
    81  
    82  	if username != gist.Owner.Login {
    83  		return fmt.Errorf("You do not own this gist.")
    84  	}
    85  
    86  	err = deleteGist(apiClient, host, gistID)
    87  	if err != nil {
    88  		return err
    89  	}
    90  
    91  	return nil
    92  }
    93  
    94  func deleteGist(apiClient *api.Client, hostname string, gistID string) error {
    95  	path := "gists/" + gistID
    96  	err := apiClient.REST(hostname, "DELETE", path, nil, nil)
    97  	if err != nil {
    98  		return err
    99  	}
   100  	return nil
   101  }