github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/cli/command/utils.go (about)

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