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.

77 lines
1.6 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. func Exit(s string) {
  28. fmt.Printf(s + "\n")
  29. os.Exit(1)
  30. }
  31. // EnsureDir ensures the given directory exists, creating it if necessary.
  32. // Errors if the path already exists as a non-directory.
  33. func EnsureDir(dir string, mode os.FileMode) error {
  34. err := os.MkdirAll(dir, mode)
  35. if err != nil {
  36. return fmt.Errorf("could not create directory %q: %w", dir, err)
  37. }
  38. return nil
  39. }
  40. func FileExists(filePath string) bool {
  41. _, err := os.Stat(filePath)
  42. return !os.IsNotExist(err)
  43. }
  44. // CopyFile copies a file. It truncates the destination file if it exists.
  45. func CopyFile(src, dst string) error {
  46. srcfile, err := os.Open(src)
  47. if err != nil {
  48. return err
  49. }
  50. defer srcfile.Close()
  51. info, err := srcfile.Stat()
  52. if err != nil {
  53. return err
  54. }
  55. if info.IsDir() {
  56. return errors.New("cannot read from directories")
  57. }
  58. // create new file, truncate if exists and apply same permissions as the original one
  59. dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm())
  60. if err != nil {
  61. return err
  62. }
  63. defer dstfile.Close()
  64. _, err = io.Copy(dstfile, srcfile)
  65. return err
  66. }