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