github.com/kbehouse/nsc@v0.0.6/cmd/listeditor.go (about)

     1  /*
     2   * Copyright 2018-2019 The NATS Authors
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   * http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15  
    16  package cmd
    17  
    18  import (
    19  	"fmt"
    20  
    21  	cli "github.com/nats-io/cliprompts/v2"
    22  )
    23  
    24  type ListEditorParam struct {
    25  	PromptMessage string
    26  	AddMessage    string
    27  	FlagName      string
    28  	Values        []string
    29  	ValidatorFn   cli.Validator
    30  }
    31  
    32  func (e *ListEditorParam) Valid() error {
    33  	if e.ValidatorFn == nil {
    34  		return nil
    35  	}
    36  	for _, v := range e.Values {
    37  		if err := e.ValidatorFn(v); err != nil {
    38  			return err
    39  		}
    40  	}
    41  	return nil
    42  }
    43  
    44  func (e *ListEditorParam) GetValues() []string {
    45  	return e.Values
    46  }
    47  
    48  func (e *ListEditorParam) Edit() error {
    49  	if e.PromptMessage == "" {
    50  		e.PromptMessage = fmt.Sprintf("edit %s", e.FlagName)
    51  	}
    52  	if e.AddMessage == "" {
    53  		e.AddMessage = fmt.Sprintf("add %s", e.FlagName)
    54  	}
    55  	for i, v := range e.Values {
    56  		sv, err := cli.Prompt(e.PromptMessage, v, cli.Val(e.ValidatorFn))
    57  		if err != nil {
    58  			return err
    59  		}
    60  		e.Values[i] = sv
    61  	}
    62  	for {
    63  		ok, err := cli.Confirm(e.AddMessage, true)
    64  		if err != nil {
    65  			return err
    66  		}
    67  		if !ok {
    68  			break
    69  		}
    70  		sv, err := cli.Prompt(e.PromptMessage, "", cli.Val(e.ValidatorFn))
    71  		if err != nil {
    72  			return err
    73  		}
    74  		e.Values = append(e.Values, sv)
    75  	}
    76  	return nil
    77  }