1 package org.apache.felix.bundleplugin;
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 =
58 thingDirectories.size() < relativeToDirectories.size() ? thingDirectories.size()
59 : relativeToDirectories.size();
60
61 int lastCommonRoot = -1;
62 int index;
63
64
65 for ( index = 0; index < length; index++ )
66 {
67 if ( thingDirectories.get( index ).equals( relativeToDirectories.get( index ) ) )
68 {
69 lastCommonRoot = index;
70 }
71 else
72 {
73 break;
74 }
75 }
76 if ( lastCommonRoot != -1 )
77 {
78
79 relativePath = new StringBuilder();
80
81 for ( index = lastCommonRoot + 1; index < relativeToDirectories.size(); index++ )
82 {
83 relativePath.append( "../" );
84 }
85
86
87 for ( index = lastCommonRoot + 1; index < thingDirectories.size(); index++ )
88 {
89 relativePath.append( thingDirectories.get( index ) ).append( '/' );
90 }
91 relativePath.append( thing.getName() );
92 return relativePath.toString();
93 }
94 return null;
95 }
96
97 static List<String> parentDirs( File of )
98 {
99 List<String> results = new ArrayList<String>();
100 for ( File p = of.getParentFile() ; p != null ; p = p.getParentFile() )
101 {
102 if ( !"".equals( p.getName() ) )
103 {
104 results.add( p.getName() );
105 }
106 }
107
108 Collections.reverse( results );
109 return results;
110 }
111 }