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