github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cmd/deletecmd/delete_repo.go (about)

     1  package deletecmd
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/olli-ai/jx/v2/pkg/cmd/create/options"
     8  
     9  	"github.com/olli-ai/jx/v2/pkg/cmd/helper"
    10  	"gopkg.in/AlecAivazis/survey.v1"
    11  
    12  	"github.com/jenkins-x/jx-logging/pkg/log"
    13  	"github.com/olli-ai/jx/v2/pkg/auth"
    14  	"github.com/olli-ai/jx/v2/pkg/cmd/opts"
    15  	"github.com/olli-ai/jx/v2/pkg/cmd/templates"
    16  	"github.com/olli-ai/jx/v2/pkg/gits"
    17  	"github.com/olli-ai/jx/v2/pkg/util"
    18  	"github.com/spf13/cobra"
    19  )
    20  
    21  var (
    22  	deleteRepoLong = templates.LongDesc(`
    23  		Deletes one or more repositories.
    24  
    25  		This command will require the delete repo role on your Persona Access Token. 
    26  
    27  		Note that command will ask for confirmation before doing anything!
    28  `)
    29  
    30  	deleteRepoExample = templates.Examples(`
    31  		# Selects the repositories to delete from the given GitHub organisation
    32  		jx delete repo --github --org myname 
    33  
    34          # Selects all the repositories in organisation myname that contain 'foo'
    35          # you get a chance to select which ones not to delete
    36  		jx delete repo --github --org myname --all --filter foo 
    37  	`)
    38  )
    39  
    40  // DeleteRepoOptions the options for the create spring command
    41  type DeleteRepoOptions struct {
    42  	options.CreateOptions
    43  
    44  	Organisation string
    45  	Repositories []string
    46  	GitHost      string
    47  	GitHub       bool
    48  	SelectAll    bool
    49  	SelectFilter string
    50  }
    51  
    52  // NewCmdDeleteRepo creates a command object for the "delete repo" command
    53  func NewCmdDeleteRepo(commonOpts *opts.CommonOptions) *cobra.Command {
    54  	options := &DeleteRepoOptions{
    55  		CreateOptions: options.CreateOptions{
    56  			CommonOptions: commonOpts,
    57  		},
    58  	}
    59  
    60  	cmd := &cobra.Command{
    61  		Use:     "repo",
    62  		Short:   "Deletes one or more Git repositories",
    63  		Aliases: []string{"repository", "repos"},
    64  		Long:    deleteRepoLong,
    65  		Example: deleteRepoExample,
    66  		Run: func(cmd *cobra.Command, args []string) {
    67  			options.Cmd = cmd
    68  			options.Args = args
    69  			err := options.Run()
    70  			helper.CheckErr(err)
    71  		},
    72  	}
    73  	//addDeleteFlags(cmd, &options.CreateOptions)
    74  
    75  	cmd.Flags().StringVarP(&options.Organisation, "org", "o", "", "Specify the Git provider organisation that includes the repository to delete")
    76  	cmd.Flags().StringArrayVarP(&options.Repositories, "name", "n", []string{}, "Specify the Git repository names to delete")
    77  	cmd.Flags().StringVarP(&options.GitHost, "git-host", "g", "", "The Git server host if not using GitHub")
    78  	cmd.Flags().BoolVarP(&options.GitHub, "github", "", false, "If you wish to pick the repositories from GitHub to import")
    79  	cmd.Flags().BoolVarP(&options.SelectAll, "all", "a", false, "If selecting projects to delete from a Git provider this defaults to selecting them all")
    80  	cmd.Flags().StringVarP(&options.SelectFilter, "filter", "f", "", "If selecting projects to delete from a Git provider this filters the list of repositories")
    81  	return cmd
    82  }
    83  
    84  // Run implements the command
    85  func (o *DeleteRepoOptions) Run() error {
    86  	surveyOpts := survey.WithStdio(o.In, o.Out, o.Err)
    87  	authConfigSvc, err := o.GitAuthConfigService()
    88  	if err != nil {
    89  		return err
    90  	}
    91  	var server *auth.AuthServer
    92  	config := authConfigSvc.Config()
    93  	if o.GitHub {
    94  		server = config.GetOrCreateServer(gits.GitHubURL)
    95  	} else {
    96  		if o.GitHost != "" {
    97  			server = config.GetOrCreateServer(o.GitHost)
    98  		} else {
    99  			server, err = config.PickServer("Pick the Git server to search for repositories", o.BatchMode, o.GetIOFileHandles())
   100  			if err != nil {
   101  				return err
   102  			}
   103  		}
   104  	}
   105  	if server == nil {
   106  		return fmt.Errorf("No Git server provided")
   107  	}
   108  	userAuth, err := config.PickServerUserAuth(server, "Git user name", o.BatchMode, "", o.GetIOFileHandles())
   109  	if err != nil {
   110  		return err
   111  	}
   112  	provider, err := gits.CreateProvider(server, userAuth, o.Git())
   113  	if err != nil {
   114  		return err
   115  	}
   116  	username := userAuth.Username
   117  	org := o.Organisation
   118  	if org == "" {
   119  		org, err = gits.PickOrganisation(provider, username, o.GetIOFileHandles())
   120  		if err != nil {
   121  			return err
   122  		}
   123  	}
   124  
   125  	if org == "" {
   126  		org = username
   127  	}
   128  
   129  	names := o.Repositories
   130  	if len(names) == 0 {
   131  		repos, err := gits.PickRepositories(provider, org, "Which repositories do you want to delete:", o.SelectAll, o.SelectFilter, o.GetIOFileHandles())
   132  		if err != nil {
   133  			return err
   134  		}
   135  
   136  		for _, r := range repos {
   137  			names = append(names, r.Name)
   138  		}
   139  	}
   140  
   141  	if !o.BatchMode {
   142  		log.Logger().Warnf("You are about to delete these repositories '%s' on the Git provider. This operation CANNOT be undone!",
   143  			strings.Join(names, ","))
   144  
   145  		flag := false
   146  		prompt := &survey.Confirm{
   147  			Message: "Are you sure you want to delete these all these repositories?",
   148  			Default: false,
   149  		}
   150  		err = survey.AskOne(prompt, &flag, nil, surveyOpts)
   151  		if err != nil {
   152  			return err
   153  		}
   154  		if !flag {
   155  			return nil
   156  		}
   157  	}
   158  
   159  	owner := org
   160  	if owner == "" {
   161  		owner = username
   162  	}
   163  	info := util.ColorInfo
   164  	for _, name := range names {
   165  		err = provider.DeleteRepository(owner, name)
   166  		if err != nil {
   167  			log.Logger().Warnf("Ensure Git Token has delete repo permissions or manually delete, for GitHub check https://github.com/settings/tokens")
   168  			log.Logger().Warnf("%s", err)
   169  		} else {
   170  			log.Logger().Infof("Deleted repository %s/%s", info(owner), info(name))
   171  		}
   172  	}
   173  	return nil
   174  }