1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.plugins.shade.mojo;
20
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25
26
27
28
29 public final class RelativizePath {
30 private RelativizePath() {
31
32 }
33
34
35
36
37
38
39
40
41 static String convertToRelativePath(File thing, File relativeTo) {
42 StringBuilder relativePath;
43
44 if (thing.getParentFile().equals(relativeTo.getParentFile())) {
45 return thing.getName();
46 }
47
48 List<String> thingDirectories = RelativizePath.parentDirs(thing);
49 List<String> relativeToDirectories = RelativizePath.parentDirs(relativeTo);
50
51
52 int length = Math.min(thingDirectories.size(), relativeToDirectories.size());
53
54 int lastCommonRoot = -1;
55 int index;
56
57
58 for (index = 0; index < length; index++) {
59 if (thingDirectories.get(index).equals(relativeToDirectories.get(index))) {
60 lastCommonRoot = index;
61 } else {
62 break;
63 }
64 }
65 if (lastCommonRoot != -1) {
66
67 relativePath = new StringBuilder();
68
69 for (index = lastCommonRoot + 1; index < relativeToDirectories.size(); index++) {
70 relativePath.append("../");
71 }
72
73
74 for (index = lastCommonRoot + 1; index < thingDirectories.size(); index++) {
75 relativePath.append(thingDirectories.get(index)).append('/');
76 }
77 relativePath.append(thing.getName());
78 return relativePath.toString();
79 }
80 return null;
81 }
82
83 static List<String> parentDirs(File of) {
84 List<String> results = new ArrayList<>();
85 for (File p = of.getParentFile(); p != null; p = p.getParentFile()) {
86 if (!"".equals(p.getName())) {
87 results.add(p.getName());
88 }
89 }
90
91 Collections.reverse(results);
92 return results;
93 }
94 }