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.

82 lines
1.7 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package common
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/signal"
  7. "syscall"
  8. )
  9. type logger interface {
  10. Info(msg string, keyvals ...interface{})
  11. }
  12. // TrapSignal catches the SIGTERM/SIGINT and executes cb function. After that it exits
  13. // with code 0.
  14. func TrapSignal(logger logger, cb func()) {
  15. c := make(chan os.Signal, 1)
  16. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  17. go func() {
  18. for sig := range c {
  19. logger.Info(fmt.Sprintf("captured %v, exiting...", sig))
  20. if cb != nil {
  21. cb()
  22. }
  23. os.Exit(0)
  24. }
  25. }()
  26. }
  27. // Kill the running process by sending itself SIGTERM.
  28. func Kill() error {
  29. p, err := os.FindProcess(os.Getpid())
  30. if err != nil {
  31. return err
  32. }
  33. return p.Signal(syscall.SIGTERM)
  34. }
  35. func Exit(s string) {
  36. fmt.Printf(s + "\n")
  37. os.Exit(1)
  38. }
  39. func EnsureDir(dir string, mode os.FileMode) error {
  40. if _, err := os.Stat(dir); os.IsNotExist(err) {
  41. err := os.MkdirAll(dir, mode)
  42. if err != nil {
  43. return fmt.Errorf("could not create directory %v. %v", dir, err)
  44. }
  45. }
  46. return nil
  47. }
  48. func FileExists(filePath string) bool {
  49. _, err := os.Stat(filePath)
  50. return !os.IsNotExist(err)
  51. }
  52. func ReadFile(filePath string) ([]byte, error) {
  53. return ioutil.ReadFile(filePath)
  54. }
  55. func MustReadFile(filePath string) []byte {
  56. fileBytes, err := ioutil.ReadFile(filePath)
  57. if err != nil {
  58. Exit(fmt.Sprintf("MustReadFile failed: %v", err))
  59. return nil
  60. }
  61. return fileBytes
  62. }
  63. func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
  64. return ioutil.WriteFile(filePath, contents, mode)
  65. }
  66. func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
  67. err := WriteFile(filePath, contents, mode)
  68. if err != nil {
  69. Exit(fmt.Sprintf("MustWriteFile failed: %v", err))
  70. }
  71. }