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.

62 lines
1.4 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.
  43. err := ioutil.WriteFile(filePath, newBytes, 0600)
  44. if err != nil {
  45. return fmt.Errorf("Failed to write file %v. %v", filePath, err)
  46. }
  47. return nil
  48. }
  49. func EnsureDir(dir string) error {
  50. if _, err := os.Stat(dir); os.IsNotExist(err) {
  51. err := os.MkdirAll(dir, 0700)
  52. if err != nil {
  53. return fmt.Errorf("Could not create directory %v. %v", dir, err)
  54. }
  55. }
  56. return nil
  57. }