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.

72 lines
1.5 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
  1. package os
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. )
  10. type logger interface {
  11. Info(msg string, keyvals ...interface{})
  12. }
  13. // TrapSignal catches SIGTERM and SIGINT, executes the cleanup function,
  14. // and exits with code 0.
  15. func TrapSignal(logger logger, cb func()) {
  16. c := make(chan os.Signal, 1)
  17. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  18. go func() {
  19. sig := <-c
  20. logger.Info(fmt.Sprintf("captured %v, exiting...", sig))
  21. if cb != nil {
  22. cb()
  23. }
  24. os.Exit(0)
  25. }()
  26. }
  27. // EnsureDir ensures the given directory exists, creating it if necessary.
  28. // Errors if the path already exists as a non-directory.
  29. func EnsureDir(dir string, mode os.FileMode) error {
  30. err := os.MkdirAll(dir, mode)
  31. if err != nil {
  32. return fmt.Errorf("could not create directory %q: %w", dir, err)
  33. }
  34. return nil
  35. }
  36. func FileExists(filePath string) bool {
  37. _, err := os.Stat(filePath)
  38. return !os.IsNotExist(err)
  39. }
  40. // CopyFile copies a file. It truncates the destination file if it exists.
  41. func CopyFile(src, dst string) error {
  42. srcfile, err := os.Open(src)
  43. if err != nil {
  44. return err
  45. }
  46. defer srcfile.Close()
  47. info, err := srcfile.Stat()
  48. if err != nil {
  49. return err
  50. }
  51. if info.IsDir() {
  52. return errors.New("cannot read from directories")
  53. }
  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. }