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.

50 lines
1.1 KiB

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. )
  8. // EnsureDir ensures the given directory exists, creating it if necessary.
  9. // Errors if the path already exists as a non-directory.
  10. func EnsureDir(dir string, mode os.FileMode) error {
  11. err := os.MkdirAll(dir, mode)
  12. if err != nil {
  13. return fmt.Errorf("could not create directory %q: %w", dir, err)
  14. }
  15. return nil
  16. }
  17. func FileExists(filePath string) bool {
  18. _, err := os.Stat(filePath)
  19. return !os.IsNotExist(err)
  20. }
  21. // CopyFile copies a file. It truncates the destination file if it exists.
  22. func CopyFile(src, dst string) error {
  23. srcfile, err := os.Open(src)
  24. if err != nil {
  25. return err
  26. }
  27. defer srcfile.Close()
  28. info, err := srcfile.Stat()
  29. if err != nil {
  30. return err
  31. }
  32. if info.IsDir() {
  33. return errors.New("cannot read from directories")
  34. }
  35. // create new file, truncate if exists and apply same permissions as the original one
  36. dstfile, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode().Perm())
  37. if err != nil {
  38. return err
  39. }
  40. defer dstfile.Close()
  41. _, err = io.Copy(dstfile, srcfile)
  42. return err
  43. }