utils.go 1.8 KB

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