github.com/olljanat/moby@v1.13.1/cli/command/utils.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  	"path/filepath"
     9  	"runtime"
    10  	"strings"
    11  )
    12  
    13  // CopyToFile writes the content of the reader to the specified file
    14  func CopyToFile(outfile string, r io.Reader) error {
    15  	tmpFile, err := ioutil.TempFile(filepath.Dir(outfile), ".docker_temp_")
    16  	if err != nil {
    17  		return err
    18  	}
    19  
    20  	tmpPath := tmpFile.Name()
    21  
    22  	_, err = io.Copy(tmpFile, r)
    23  	tmpFile.Close()
    24  
    25  	if err != nil {
    26  		os.Remove(tmpPath)
    27  		return err
    28  	}
    29  
    30  	if err = os.Rename(tmpPath, outfile); err != nil {
    31  		os.Remove(tmpPath)
    32  		return err
    33  	}
    34  
    35  	return nil
    36  }
    37  
    38  // capitalizeFirst capitalizes the first character of string
    39  func capitalizeFirst(s string) string {
    40  	switch l := len(s); l {
    41  	case 0:
    42  		return s
    43  	case 1:
    44  		return strings.ToLower(s)
    45  	default:
    46  		return strings.ToUpper(string(s[0])) + strings.ToLower(s[1:])
    47  	}
    48  }
    49  
    50  // PrettyPrint outputs arbitrary data for human formatted output by uppercasing the first letter.
    51  func PrettyPrint(i interface{}) string {
    52  	switch t := i.(type) {
    53  	case nil:
    54  		return "None"
    55  	case string:
    56  		return capitalizeFirst(t)
    57  	default:
    58  		return capitalizeFirst(fmt.Sprintf("%s", t))
    59  	}
    60  }
    61  
    62  // PromptForConfirmation requests and checks confirmation from user.
    63  // This will display the provided message followed by ' [y/N] '. If
    64  // the user input 'y' or 'Y' it returns true other false.  If no
    65  // message is provided "Are you sure you want to proceed? [y/N] "
    66  // will be used instead.
    67  func PromptForConfirmation(ins *InStream, outs *OutStream, message string) bool {
    68  	if message == "" {
    69  		message = "Are you sure you want to proceed?"
    70  	}
    71  	message += " [y/N] "
    72  
    73  	fmt.Fprintf(outs, message)
    74  
    75  	// On Windows, force the use of the regular OS stdin stream.
    76  	if runtime.GOOS == "windows" {
    77  		ins = NewInStream(os.Stdin)
    78  	}
    79  
    80  	answer := ""
    81  	n, _ := fmt.Fscan(ins, &answer)
    82  	if n != 1 || (answer != "y" && answer != "Y") {
    83  		return false
    84  	}
    85  
    86  	return true
    87  }