Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PathResolver {
- String relativePath(String path1, String path2) {
- [path1, path2].each{ checkPath(it) }
- def (from, to) = cutCommonBaseDir(path1, path2)
- (baseDir(from).replaceAll('[^/]+/', '../') ?: './') + to
- }
- private checkPath(path) {
- if (!path.startsWith('/')) {
- throw new IllegalArgumentException("It's not an absolute path: $path")
- }
- if (!path) {
- throw new IllegalArgumentException("Empty: $path")
- }
- if (path.find($/[\?*:|<>]/$)) {
- throw new IllegalArgumentException("Invalid chars: $path")
- }
- }
- private cutCommonBaseDir(path1, path2) {
- def commonBaseDir = commonBaseDir(path1, path2)
- [path1, path2].collect{ it.replaceFirst(commonBaseDir, '') }
- }
- private String commonBaseDir(path1, path2) {
- def result = []
- def splitPathToken = { baseDir(it).split('/') }
- def tokens1 = splitPathToken(path1)
- def tokens2 = splitPathToken(path2)
- for (int i : 0..<[tokens1, tokens2]*.size().min()) {
- if (tokens1[i] != tokens2[i]) break
- result << tokens1[i]
- }
- result << ''
- result.join('/')
- }
- private String baseDir(path) {
- path.replaceFirst('[^/]*$', '')
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement