github.com/solo-io/cue@v0.4.7/pkg/tool/cli/cli.go (about)

     1  // Copyright 2019 CUE Authors
     2  //
     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  package cli
    16  
    17  //go:generate go run gen.go
    18  //go:generate gofmt -s -w .
    19  
    20  import (
    21  	"fmt"
    22  	"strings"
    23  
    24  	"github.com/solo-io/cue/cue"
    25  	"github.com/solo-io/cue/internal/task"
    26  )
    27  
    28  func init() {
    29  	task.Register("tool/cli.Print", newPrintCmd)
    30  	task.Register("tool/cli.Ask", newAskCmd)
    31  
    32  	// For backwards compatibility.
    33  	task.Register("print", newPrintCmd)
    34  }
    35  
    36  type printCmd struct{}
    37  
    38  func newPrintCmd(v cue.Value) (task.Runner, error) {
    39  	return &printCmd{}, nil
    40  }
    41  
    42  func (c *printCmd) Run(ctx *task.Context) (res interface{}, err error) {
    43  	str := ctx.String("text")
    44  	if ctx.Err != nil {
    45  		return nil, ctx.Err
    46  	}
    47  	fmt.Fprintln(ctx.Stdout, str)
    48  	return nil, nil
    49  }
    50  
    51  type askCmd struct{}
    52  
    53  func newAskCmd(v cue.Value) (task.Runner, error) {
    54  	return &askCmd{}, nil
    55  }
    56  
    57  func (c *askCmd) Run(ctx *task.Context) (res interface{}, err error) {
    58  	str := ctx.String("prompt")
    59  	if ctx.Err != nil {
    60  		return nil, ctx.Err
    61  	}
    62  	if str != "" {
    63  		fmt.Fprint(ctx.Stdout, str+" ")
    64  	}
    65  
    66  	var response string
    67  	if _, err := fmt.Scan(&response); err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	update := map[string]interface{}{"response": response}
    72  
    73  	switch v := ctx.Lookup("response"); v.IncompleteKind() {
    74  	case cue.BoolKind:
    75  		switch strings.ToLower(response) {
    76  		case "yes":
    77  			update["response"] = true
    78  		default:
    79  			update["response"] = false
    80  		}
    81  	case cue.StringKind:
    82  		// already set above
    83  	}
    84  	return update, nil
    85  }