You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.2 KiB

10 years ago
  1. package common
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/signal"
  7. )
  8. func TrapSignal(cb func()) {
  9. c := make(chan os.Signal, 1)
  10. signal.Notify(c, os.Interrupt)
  11. signal.Notify(c, os.Kill)
  12. go func() {
  13. for sig := range c {
  14. fmt.Printf("captured %v, exiting...\n", sig)
  15. if cb != nil {
  16. cb()
  17. }
  18. os.Exit(1)
  19. }
  20. }()
  21. select {}
  22. }
  23. func Exit(s string) {
  24. fmt.Printf(s + "\n")
  25. os.Exit(1)
  26. }
  27. func EnsureDir(dir string) error {
  28. if _, err := os.Stat(dir); os.IsNotExist(err) {
  29. err := os.MkdirAll(dir, 0700)
  30. if err != nil {
  31. return fmt.Errorf("Could not create directory %v. %v", dir, err)
  32. }
  33. }
  34. return nil
  35. }
  36. func FileExists(filePath string) bool {
  37. _, err := os.Stat(filePath)
  38. return !os.IsNotExist(err)
  39. }
  40. func ReadFile(filePath string) ([]byte, error) {
  41. return ioutil.ReadFile(filePath)
  42. }
  43. func MustReadFile(filePath string) []byte {
  44. fileBytes, err := ioutil.ReadFile(filePath)
  45. if err != nil {
  46. Exit(Fmt("MustReadFile failed: %v", err))
  47. return nil
  48. }
  49. return fileBytes
  50. }
  51. func WriteFile(filePath string, contents []byte) error {
  52. err := ioutil.WriteFile(filePath, contents, 0600)
  53. if err != nil {
  54. return err
  55. }
  56. fmt.Printf("File written to %v.\n", filePath)
  57. return nil
  58. }
  59. func MustWriteFile(filePath string, contents []byte) {
  60. err := WriteFile(filePath, contents)
  61. if err != nil {
  62. Exit(Fmt("MustWriteFile failed: %v", err))
  63. }
  64. }
  65. // Writes to newBytes to filePath.
  66. // Guaranteed not to lose *both* oldBytes and newBytes,
  67. // (assuming that the OS is perfect)
  68. func WriteFileAtomic(filePath string, newBytes []byte) error {
  69. // If a file already exists there, copy to filePath+".bak" (overwrite anything)
  70. if _, err := os.Stat(filePath); !os.IsNotExist(err) {
  71. fileBytes, err := ioutil.ReadFile(filePath)
  72. if err != nil {
  73. return fmt.Errorf("Could not read file %v. %v", filePath, err)
  74. }
  75. err = ioutil.WriteFile(filePath+".bak", fileBytes, 0600)
  76. if err != nil {
  77. return fmt.Errorf("Could not write file %v. %v", filePath+".bak", err)
  78. }
  79. }
  80. // Write newBytes to filePath.new
  81. err := ioutil.WriteFile(filePath+".new", newBytes, 0600)
  82. if err != nil {
  83. return fmt.Errorf("Could not write file %v. %v", filePath+".new", err)
  84. }
  85. // Move filePath.new to filePath
  86. err = os.Rename(filePath+".new", filePath)
  87. return err
  88. }