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.

64 lines
1.5 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. // Writes to newBytes to filePath.
  28. // Guaranteed not to lose *both* oldBytes and newBytes,
  29. // (assuming that the OS is perfect)
  30. func AtomicWriteFile(filePath string, newBytes []byte) error {
  31. // If a file already exists there, copy to filePath+".bak" (overwrite anything)
  32. if _, err := os.Stat(filePath); !os.IsNotExist(err) {
  33. fileBytes, err := ioutil.ReadFile(filePath)
  34. if err != nil {
  35. return fmt.Errorf("Failed to read file %v. %v", filePath, err)
  36. }
  37. err = ioutil.WriteFile(filePath+".bak", fileBytes, 0600)
  38. if err != nil {
  39. return fmt.Errorf("Failed to write file %v. %v", filePath+".bak", err)
  40. }
  41. }
  42. // Write newBytes to filePath.new
  43. err := ioutil.WriteFile(filePath+".new", newBytes, 0600)
  44. if err != nil {
  45. return fmt.Errorf("Failed to write file %v. %v", filePath+".new", err)
  46. }
  47. // Move filePath.new to filePath
  48. err = os.Rename(filePath+".new", filePath)
  49. return err
  50. }
  51. func EnsureDir(dir string) error {
  52. if _, err := os.Stat(dir); os.IsNotExist(err) {
  53. err := os.MkdirAll(dir, 0700)
  54. if err != nil {
  55. return fmt.Errorf("Could not create directory %v. %v", dir, err)
  56. }
  57. }
  58. return nil
  59. }