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.

73 lines
1.4 KiB

9 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
9 years ago
  1. package os
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "os/signal"
  7. "syscall"
  8. )
  9. type logger interface {
  10. Info(msg string, keyvals ...interface{})
  11. }
  12. // TrapSignal catches SIGTERM and SIGINT, executes the cleanup function,
  13. // and exits 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. sig := <-c
  19. logger.Info(fmt.Sprintf("captured %v, exiting...", sig))
  20. if cb != nil {
  21. cb()
  22. }
  23. os.Exit(0)
  24. }()
  25. }
  26. func Exit(s string) {
  27. fmt.Printf(s + "\n")
  28. os.Exit(1)
  29. }
  30. func EnsureDir(dir string, mode os.FileMode) error {
  31. if _, err := os.Stat(dir); os.IsNotExist(err) {
  32. err := os.MkdirAll(dir, mode)
  33. if err != nil {
  34. return fmt.Errorf("could not create directory %v: %w", dir, err)
  35. }
  36. }
  37. return nil
  38. }
  39. func FileExists(filePath string) bool {
  40. _, err := os.Stat(filePath)
  41. return !os.IsNotExist(err)
  42. }
  43. // CopyFile copies a file. It truncates the destination file if it exists.
  44. func CopyFile(src, dst string) error {
  45. info, err := os.Stat(src)
  46. if err != nil {
  47. return err
  48. }
  49. srcfile, err := os.Open(src)
  50. if err != nil {
  51. return err
  52. }
  53. defer srcfile.Close()
  54. // create new file, truncate if exists and apply same permissions as the original one
  55. dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm())
  56. if err != nil {
  57. return err
  58. }
  59. defer dstfile.Close()
  60. _, err = io.Copy(dstfile, srcfile)
  61. return err
  62. }