utils.go 2.0 KB

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