github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/cli/command/utils.go (about)

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