...

Source file src/github.com/sigstore/cosign/v2/internal/ui/prompt.go

Documentation: github.com/sigstore/cosign/v2/internal/ui

     1  // Copyright 2023 The Sigstore 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  package ui
    15  
    16  import (
    17  	"bufio"
    18  	"context"
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"strings"
    23  )
    24  
    25  type ErrPromptDeclined struct{}
    26  
    27  func (e *ErrPromptDeclined) Error() string {
    28  	return "user declined the prompt"
    29  }
    30  
    31  type ErrInvalidInput struct {
    32  	Got     string
    33  	Allowed string
    34  }
    35  
    36  func (e *ErrInvalidInput) Error() string {
    37  	return fmt.Sprintf("invalid input %#v (allowed values %v)", e.Got, e.Allowed)
    38  }
    39  
    40  func newInvalidYesOrNoInput(got string) error {
    41  	return &ErrInvalidInput{Got: got, Allowed: "y, n"}
    42  }
    43  
    44  func (w *Env) prompt() error {
    45  	fmt.Fprint(w.Stderr, "Are you sure you would like to continue? [y/N] ")
    46  
    47  	// TODO: what if it's not a terminal?
    48  	r, err := bufio.NewReader(w.Stdin).ReadString('\n')
    49  	if err != nil && !errors.Is(err, io.EOF) {
    50  		return err
    51  	}
    52  
    53  	value := strings.Trim(r, "\r\n")
    54  	switch strings.ToLower(value) {
    55  	case "y":
    56  		return nil
    57  	case "":
    58  		fallthrough // TODO: allow setting default=true?
    59  	case "n":
    60  		return &ErrPromptDeclined{}
    61  	default:
    62  		// TODO: allow retry on invalid input?
    63  		return newInvalidYesOrNoInput(value)
    64  	}
    65  }
    66  
    67  // ConfirmContinue prompts the user whether they would like to continue and
    68  // returns the parsed answer.
    69  //
    70  // If the user enters anything other than "y" or "Y", ConfirmContinue returns an
    71  // error.
    72  func ConfirmContinue(ctx context.Context) error {
    73  	return getEnv(ctx).prompt()
    74  }
    75  

View as plain text