github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/list/instances/instances.go (about)

     1  package listinstances
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/henvic/ctxsignal"
     8  	"github.com/henvic/wedeploycli/cmdflagsfromhost"
     9  	"github.com/henvic/wedeploycli/color"
    10  	"github.com/henvic/wedeploycli/command/internal/we"
    11  	"github.com/henvic/wedeploycli/list"
    12  	"github.com/henvic/wedeploycli/listinstances"
    13  	"github.com/henvic/wedeploycli/services"
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  // ListInstancesCmd is used for getting a list of projects and services
    18  var ListInstancesCmd = &cobra.Command{
    19  	Use: "instances",
    20  	Example: `  lcp list instances --project chat --service data
    21    lcp list instances --url data-chat.lfr.cloud`,
    22  	Short:   "Show list of instances",
    23  	Args:    cobra.NoArgs,
    24  	PreRunE: preRun,
    25  	RunE:    listRun,
    26  }
    27  
    28  var watch bool
    29  
    30  var setupHost = cmdflagsfromhost.SetupHost{
    31  	Pattern: cmdflagsfromhost.FullHostPattern,
    32  
    33  	Requires: cmdflagsfromhost.Requires{
    34  		Auth:    true,
    35  		Project: true,
    36  		Service: true,
    37  	},
    38  
    39  	PromptMissingService: true,
    40  
    41  	ListExtraDetails: list.Instances,
    42  }
    43  
    44  func preRun(cmd *cobra.Command, args []string) error {
    45  	return setupHost.Process(context.Background(), we.Context())
    46  }
    47  
    48  func listRun(cmd *cobra.Command, args []string) error {
    49  	servicesClient := services.New(we.Context())
    50  
    51  	instances, err := servicesClient.Instances(context.Background(), setupHost.Project(), setupHost.Service())
    52  
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	if len(instances) == 0 {
    58  		return fmt.Errorf("no instances found for service %s", setupHost.Service())
    59  	}
    60  
    61  	li := listinstances.New(setupHost.Project(), setupHost.Service())
    62  
    63  	if !watch {
    64  		return li.Once(context.Background(), we.Context())
    65  	}
    66  
    67  	fmt.Println(color.Format(color.FgHiBlack,
    68  		"List of instances will be updated when a change occurs.\n"))
    69  
    70  	ctx, cancel := ctxsignal.WithTermination(context.Background())
    71  	defer cancel()
    72  
    73  	li.Watch(ctx, we.Context())
    74  
    75  	if _, err = ctxsignal.Closed(ctx); err == nil {
    76  		fmt.Println()
    77  	}
    78  
    79  	return nil
    80  }
    81  
    82  func init() {
    83  	setupHost.Init(ListInstancesCmd)
    84  	ListInstancesCmd.Flags().BoolVarP(&watch, "watch", "w", false, "Show and watch for changes")
    85  }