utils.go 2.0 KB

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