1 package org.apache.maven.plugin.reactor;
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.Iterator;
24 import java.util.LinkedList;
25
26
27
28
29
30
31 class RelativePather {
32
33
34
35
36
37
38 public static String getRelativePath(File context, File dest) {
39 LinkedList contextChunks = getPathChunks(context);
40 LinkedList destChunks = getPathChunks(dest);
41 if (!contextChunks.getFirst().equals(destChunks.getFirst())) throw new DifferentRootsException("Roots differ");
42 int count = 0;
43 Iterator contextChunker = contextChunks.iterator();
44 Iterator destChunker = destChunks.iterator();
45 String contextChunk = (String) contextChunker.next();
46 String destChunk = (String) destChunker.next();
47 boolean pathsDiffer = false;
48 while (true) {
49 count++;
50 if (!contextChunker.hasNext()) break;
51 if (!destChunker.hasNext()) break;
52 contextChunk = (String) contextChunker.next();
53 destChunk = (String) destChunker.next();
54 if (!contextChunk.equals(destChunk)) {
55 pathsDiffer = true;
56 break;
57 }
58 }
59
60
61
62 StringBuffer relativePath = new StringBuffer();
63
64 if (count < contextChunks.size()) {
65 int dotDotCount = contextChunks.size() - count;
66 for (int i = 0; i < dotDotCount; i++) {
67 relativePath.append("..");
68
69 if (i < dotDotCount -1) {
70 relativePath.append(File.separatorChar);
71 }
72 }
73 }
74 if (pathsDiffer) {
75 if (relativePath.length() > 0) {
76 relativePath.append(File.separatorChar);
77 }
78 relativePath.append(destChunk);
79 }
80 while (destChunker.hasNext()) {
81 if (relativePath.length() > 0) {
82 relativePath.append(File.separatorChar);
83 }
84 relativePath.append(destChunker.next());
85 }
86
87 return relativePath.toString();
88 }
89
90 private static LinkedList getPathChunks(File f) {
91 LinkedList l = new LinkedList();
92 while (f.getParentFile() != null) {
93 l.addFirst(f.getName());
94 f = f.getParentFile();
95 }
96 l.addFirst(f.getAbsolutePath());
97 return l;
98 }
99
100 static class DifferentRootsException extends RuntimeException {
101 private static final long serialVersionUID = 1L;
102
103 public DifferentRootsException() {
104 super();
105 }
106
107 public DifferentRootsException(String message, Throwable cause) {
108 super(message, cause);
109 }
110
111 public DifferentRootsException(String message) {
112 super(message);
113 }
114
115 public DifferentRootsException(Throwable cause) {
116 super(cause);
117 }
118
119 }
120 }