utils.go 1.7 KB

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