1 package org.apache.maven.plugins.shade.mojo;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
43 static String convertToRelativePath( File thing, File relativeTo )
44 {
45 StringBuilder relativePath = null;
46
47 if ( thing.getParentFile().equals( relativeTo.getParentFile() ) )
48 {
49 return thing.getName();
50 }
51
52 List<String> thingDirectories = RelativizePath.parentDirs( thing );
53 List<String> relativeToDirectories = RelativizePath.parentDirs( relativeTo );
54
55
56 int length = thingDirectories.size() < relativeToDirectories.size() ? thingDirectories.size() : relativeToDirectories.size();
57
58 int lastCommonRoot = -1;
59 int index;
60
61
62 for ( index = 0; index < length; index++ )
63 {
64 if ( thingDirectories.get( index ).equals( relativeToDirectories.get( index ) ) )
65 {
66 lastCommonRoot = index;
67 }
68 else
69 {
70 break;
71 }
72 }
73 if ( lastCommonRoot != -1 )
74 {
75
76 relativePath = new StringBuilder();
77
78 for ( index = lastCommonRoot + 1; index < relativeToDirectories.size(); index++ )
79 {
80 relativePath.append( "../" );
81 }
82
83
84 for ( index = lastCommonRoot + 1; index < thingDirectories.size(); index++ )
85 {
86 relativePath.append( thingDirectories.get( index ) + '/' );
87 }
88 relativePath.append( thing.getName() );
89 return relativePath.toString();
90 }
91 return null;
92 }
93
94 static List<String> parentDirs( File of )
95 {
96 List<String> results = new ArrayList<String>();
97 for ( File p = of.getParentFile() ; p != null ; p = p.getParentFile() )
98 {
99 if ( !"".equals( p.getName() ) )
100 {
101 results.add( p.getName() );
102 }
103 }
104
105 Collections.reverse( results );
106 return results;
107 }
108 }