wastebasket_darwin.go 1011 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //go:build darwin && !ios
  2. package wastebasket
  3. import (
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strings"
  9. )
  10. // Trash moves a file or folder including its content into the systems trashbin.
  11. func Trash(paths ...string) error {
  12. for _, path := range paths {
  13. _, err := os.Stat(path)
  14. if os.IsNotExist(err) {
  15. continue
  16. }
  17. if err != nil {
  18. return err
  19. }
  20. //Passing a relative path will lead to the Finder not being able to find the file at all.
  21. path, pathToAbsPathError := filepath.Abs(path)
  22. if pathToAbsPathError != nil {
  23. return pathToAbsPathError
  24. }
  25. path = strings.ReplaceAll(path, `"`, `\"`)
  26. osascriptCommand := fmt.Sprintf(`tell app "Finder" to delete POSIX file "%s"`, path)
  27. err = exec.Command("osascript", "-e", osascriptCommand).Run()
  28. if err != nil {
  29. return err
  30. }
  31. }
  32. return nil
  33. }
  34. // Empty clears the platforms trashbin. It uses the `Finder` app to empty the trashbin.
  35. func Empty() error {
  36. return exec.Command("osascript", "-e", `tell app "Finder" to empty`).Run()
  37. }