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.

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