Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. class PathResolver {
  2.  
  3. String relativePath(String path1, String path2) {
  4. [path1, path2].each{ checkPath(it) }
  5. def (from, to) = cutCommonBaseDir(path1, path2)
  6. (baseDir(from).replaceAll('[^/]+/', '../') ?: './') + to
  7. }
  8.  
  9. private checkPath(path) {
  10. if (!path.startsWith('/')) {
  11. throw new IllegalArgumentException("It's not an absolute path: $path")
  12. }
  13. if (!path) {
  14. throw new IllegalArgumentException("Empty: $path")
  15. }
  16. if (path.find($/[\?*:|<>]/$)) {
  17. throw new IllegalArgumentException("Invalid chars: $path")
  18. }
  19. }
  20.  
  21. private cutCommonBaseDir(path1, path2) {
  22. def commonBaseDir = commonBaseDir(path1, path2)
  23. [path1, path2].collect{ it.replaceFirst(commonBaseDir, '') }
  24. }
  25.  
  26. private String commonBaseDir(path1, path2) {
  27. def result = []
  28. def splitPathToken = { baseDir(it).split('/') }
  29. def tokens1 = splitPathToken(path1)
  30. def tokens2 = splitPathToken(path2)
  31. for (int i : 0..<[tokens1, tokens2]*.size().min()) {
  32. if (tokens1[i] != tokens2[i]) break
  33. result << tokens1[i]
  34. }
  35. result << ''
  36. result.join('/')
  37. }
  38.  
  39. private String baseDir(path) {
  40. path.replaceFirst('[^/]*$', '')
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement