directory.go 694 B

123456789101112131415161718192021222324252627282930313233
  1. package helper
  2. import (
  3. "github.com/uozi-tech/cosy/logger"
  4. "path/filepath"
  5. "strings"
  6. )
  7. // IsUnderDirectory checks if the path is under the directory
  8. func IsUnderDirectory(path, directory string) bool {
  9. absPath, err := filepath.Abs(path)
  10. if err != nil {
  11. logger.Error(err)
  12. return false
  13. }
  14. absDirectory, err := filepath.Abs(directory)
  15. if err != nil {
  16. logger.Error(err)
  17. return false
  18. }
  19. absPath = filepath.Clean(absPath)
  20. absDirectory = filepath.Clean(absDirectory)
  21. // Check if path is exactly the directory or under it
  22. if absPath == absDirectory {
  23. return true
  24. }
  25. absDirectory = absDirectory + string(filepath.Separator)
  26. return strings.HasPrefix(absPath, absDirectory)
  27. }