-
Notifications
You must be signed in to change notification settings - Fork 33
/
UnixPath.java
509 lines (462 loc) · 15.3 KB
/
UnixPath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage.contrib.nio;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.PeekingIterator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Unix file system path.
*
* <p>This class is helpful for writing {@link java.nio.file.Path Path} implementations.
*
* <p>This implementation behaves almost identically to {@code sun.nio.fs.UnixPath}. The only
* difference is that some methods (like {@link #relativize(UnixPath)} go to greater lengths to
* preserve trailing backslashes, in order to ensure the path will continue to be recognized as a
* directory.
*
* <p><b>Note:</b> This code might not play nice with <a
* href="http://docs.oracle.com/javase/tutorial/i18n/text/supplementaryChars.html">Supplementary
* Characters as Surrogates</a>.
*/
@Immutable
final class UnixPath implements CharSequence {
public static final char DOT = '.';
public static final char SEPARATOR = '/';
public static final String ROOT = "" + SEPARATOR;
public static final String CURRENT_DIR = "" + DOT;
public static final String PARENT_DIR = "" + DOT + DOT;
public static final UnixPath EMPTY_PATH = new UnixPath(false, "");
public static final UnixPath ROOT_PATH = new UnixPath(false, ROOT);
private static final Splitter SPLITTER = Splitter.on(SEPARATOR).omitEmptyStrings();
private static final Splitter SPLITTER_PERMIT_EMPTY_COMPONENTS = Splitter.on(SEPARATOR);
private static final Joiner JOINER = Joiner.on(SEPARATOR);
private static final Ordering<Iterable<String>> ORDERING = Ordering.natural().lexicographical();
private final String path;
private List<String> lazyStringParts;
private final boolean permitEmptyComponents;
private UnixPath(boolean permitEmptyComponents, String path) {
this.path = checkNotNull(path);
this.permitEmptyComponents = permitEmptyComponents;
}
/** Returns new path of {@code first}. */
public static UnixPath getPath(boolean permitEmptyComponents, String path) {
if (path.isEmpty()) {
return EMPTY_PATH;
} else if (isRootInternal(path)) {
return ROOT_PATH;
} else {
return new UnixPath(permitEmptyComponents, path);
}
}
/**
* Returns new path of {@code first} with {@code more} components resolved against it.
*
* @see #resolve(UnixPath)
* @see java.nio.file.FileSystem#getPath(String, String...)
*/
public static UnixPath getPath(boolean permitEmptyComponents, String first, String... more) {
if (more.length == 0) {
return getPath(permitEmptyComponents, first);
}
StringBuilder builder = new StringBuilder(first);
for (int i = 0; i < more.length; i++) {
String part = more[i];
if (part.isEmpty()) {
continue;
} else if (isAbsoluteInternal(part)) {
if (i == more.length - 1) {
return new UnixPath(permitEmptyComponents, part);
} else {
builder.replace(0, builder.length(), part);
}
} else if (hasTrailingSeparatorInternal(builder)) {
builder.append(part);
} else {
builder.append(SEPARATOR);
builder.append(part);
}
}
return new UnixPath(permitEmptyComponents, builder.toString());
}
/** Returns {@code true} consists only of {@code separator}. */
public boolean isRoot() {
return isRootInternal(path);
}
private static boolean isRootInternal(String path) {
return path.length() == 1 && path.charAt(0) == SEPARATOR;
}
/** Returns {@code true} if path starts with {@code separator}. */
public boolean isAbsolute() {
return isAbsoluteInternal(path);
}
private static boolean isAbsoluteInternal(String path) {
return !path.isEmpty() && path.charAt(0) == SEPARATOR;
}
/** Returns {@code true} if path ends with {@code separator}. */
public boolean hasTrailingSeparator() {
return hasTrailingSeparatorInternal(path);
}
private static boolean hasTrailingSeparatorInternal(CharSequence path) {
return path.length() != 0 && path.charAt(path.length() - 1) == SEPARATOR;
}
/** Returns {@code true} if path ends with a trailing slash, or would after normalization. */
public boolean seemsLikeADirectory() {
int length = path.length();
return path.isEmpty()
|| path.charAt(length - 1) == SEPARATOR
|| path.endsWith(".") && (length == 1 || path.charAt(length - 2) == SEPARATOR)
|| path.endsWith("..") && (length == 2 || path.charAt(length - 3) == SEPARATOR);
}
/**
* Returns last component in {@code path}.
*
* @see java.nio.file.Path#getFileName()
*/
@Nullable
public UnixPath getFileName() {
if (path.isEmpty()) {
return EMPTY_PATH;
} else if (isRoot()) {
return null;
} else {
List<String> parts = getParts();
String last = parts.get(parts.size() - 1);
return parts.size() == 1 && path.equals(last)
? this
: new UnixPath(permitEmptyComponents, last);
}
}
/**
* Returns parent directory (including trailing separator) or {@code null} if no parent remains.
*
* @see java.nio.file.Path#getParent()
*/
@Nullable
public UnixPath getParent() {
if (path.isEmpty() || isRoot()) {
return null;
}
int index =
hasTrailingSeparator()
? path.lastIndexOf(SEPARATOR, path.length() - 2)
: path.lastIndexOf(SEPARATOR);
if (index == -1) {
return isAbsolute() ? ROOT_PATH : null;
} else {
return new UnixPath(permitEmptyComponents, path.substring(0, index + 1));
}
}
/**
* Returns root component if an absolute path, otherwise {@code null}.
*
* @see java.nio.file.Path#getRoot()
*/
@Nullable
public UnixPath getRoot() {
return isAbsolute() ? ROOT_PATH : null;
}
/**
* Returns specified range of sub-components in path joined together.
*
* @see java.nio.file.Path#subpath(int, int)
*/
public UnixPath subpath(int beginIndex, int endIndex) {
if (path.isEmpty() && beginIndex == 0 && endIndex == 1) {
return this;
}
checkArgument(beginIndex >= 0 && endIndex > beginIndex);
List<String> subList;
try {
subList = getParts().subList(beginIndex, endIndex);
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException();
}
return new UnixPath(permitEmptyComponents, JOINER.join(subList));
}
/**
* Returns number of components in {@code path}.
*
* @see java.nio.file.Path#getNameCount()
*/
public int getNameCount() {
if (path.isEmpty()) {
return 1;
} else if (isRoot()) {
return 0;
} else {
return getParts().size();
}
}
/**
* Returns component in {@code path} at {@code index}.
*
* @see java.nio.file.Path#getName(int)
*/
public UnixPath getName(int index) {
if (path.isEmpty()) {
return this;
}
try {
return new UnixPath(permitEmptyComponents, getParts().get(index));
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException();
}
}
/**
* Returns path without extra separators or {@code .} and {@code ..}, preserving trailing slash.
*
* @see java.nio.file.Path#normalize()
*/
public UnixPath normalize() {
List<String> parts = new ArrayList<>();
boolean mutated = false;
int resultLength = 0;
int mark = 0;
int index;
do {
index = path.indexOf(SEPARATOR, mark);
String part = path.substring(mark, index == -1 ? path.length() : index + 1);
switch (part) {
case CURRENT_DIR:
case CURRENT_DIR + SEPARATOR:
mutated = true;
break;
case PARENT_DIR:
case PARENT_DIR + SEPARATOR:
mutated = true;
if (!parts.isEmpty()) {
resultLength -= parts.remove(parts.size() - 1).length();
}
break;
default:
if (index != mark || index == 0) {
parts.add(part);
resultLength = part.length();
} else {
mutated = true;
}
}
mark = index + 1;
} while (index != -1);
if (!mutated) {
return this;
}
StringBuilder result = new StringBuilder(resultLength);
for (String part : parts) {
result.append(part);
}
return new UnixPath(permitEmptyComponents, result.toString());
}
/**
* Returns {@code other} appended to {@code path}.
*
* @see java.nio.file.Path#resolve(java.nio.file.Path)
*/
public UnixPath resolve(UnixPath other) {
if (other.path.isEmpty()) {
return this;
} else if (other.isAbsolute()) {
return other;
} else if (hasTrailingSeparator()) {
return new UnixPath(permitEmptyComponents, path + other.path);
} else {
return new UnixPath(permitEmptyComponents, path + SEPARATOR + other.path);
}
}
/**
* Returns {@code other} resolved against parent of {@code path}.
*
* @see java.nio.file.Path#resolveSibling(java.nio.file.Path)
*/
public UnixPath resolveSibling(UnixPath other) {
checkNotNull(other);
UnixPath parent = getParent();
return parent == null ? other : parent.resolve(other);
}
/**
* Returns {@code other} made relative to {@code path}.
*
* @see java.nio.file.Path#relativize(java.nio.file.Path)
*/
public UnixPath relativize(UnixPath other) {
checkArgument(isAbsolute() == other.isAbsolute(), "'other' is different type of Path");
if (path.isEmpty()) {
return other;
}
PeekingIterator<String> left = Iterators.peekingIterator(split());
PeekingIterator<String> right = Iterators.peekingIterator(other.split());
while (left.hasNext() && right.hasNext()) {
if (!left.peek().equals(right.peek())) {
break;
}
left.next();
right.next();
}
StringBuilder result = new StringBuilder(path.length() + other.path.length());
while (left.hasNext()) {
result.append(PARENT_DIR);
result.append(SEPARATOR);
left.next();
}
while (right.hasNext()) {
result.append(right.next());
result.append(SEPARATOR);
}
if (result.length() > 0 && !other.hasTrailingSeparator()) {
result.deleteCharAt(result.length() - 1);
}
return new UnixPath(permitEmptyComponents, result.toString());
}
/**
* Returns {@code true} if {@code path} starts with {@code other}.
*
* @see java.nio.file.Path#startsWith(java.nio.file.Path)
*/
public boolean startsWith(UnixPath other) {
UnixPath me = removeTrailingSeparator();
other = other.removeTrailingSeparator();
if (other.path.length() > me.path.length()) {
return false;
} else if (me.isAbsolute() != other.isAbsolute()) {
return false;
} else if (!me.path.isEmpty() && other.path.isEmpty()) {
return false;
}
return startsWith(split(), other.split());
}
private static boolean startsWith(Iterator<String> lefts, Iterator<String> rights) {
while (rights.hasNext()) {
if (!lefts.hasNext() || !rights.next().equals(lefts.next())) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if {@code path} ends with {@code other}.
*
* @see java.nio.file.Path#endsWith(java.nio.file.Path)
*/
public boolean endsWith(UnixPath other) {
UnixPath me = removeTrailingSeparator();
other = other.removeTrailingSeparator();
if (other.path.length() > me.path.length()) {
return false;
} else if (!me.path.isEmpty() && other.path.isEmpty()) {
return false;
} else if (other.isAbsolute()) {
return me.isAbsolute() && me.path.equals(other.path);
}
return startsWith(me.splitReverse(), other.splitReverse());
}
/**
* Compares two paths lexicographically for ordering.
*
* @see java.nio.file.Path#compareTo(java.nio.file.Path)
*/
public int compareTo(UnixPath other) {
return ORDERING.compare(getParts(), other.getParts());
}
/** Converts relative path to an absolute path. */
public UnixPath toAbsolutePath(UnixPath currentWorkingDirectory) {
checkArgument(currentWorkingDirectory.isAbsolute());
return isAbsolute() ? this : currentWorkingDirectory.resolve(this);
}
/** Returns {@code toAbsolutePath(ROOT_PATH)}. */
public UnixPath toAbsolutePath() {
return toAbsolutePath(ROOT_PATH);
}
/** Removes beginning separator from path, if an absolute path. */
public UnixPath removeBeginningSeparator() {
return isAbsolute() ? new UnixPath(permitEmptyComponents, path.substring(1)) : this;
}
/** Adds trailing separator to path, if it isn't present. */
public UnixPath addTrailingSeparator() {
return hasTrailingSeparator() ? this : new UnixPath(permitEmptyComponents, path + SEPARATOR);
}
/** Removes trailing separator from path, unless it's root. */
public UnixPath removeTrailingSeparator() {
if (!isRoot() && hasTrailingSeparator()) {
return new UnixPath(permitEmptyComponents, path.substring(0, path.length() - 1));
} else {
return this;
}
}
/** Splits path into components, excluding separators and empty strings. */
public Iterator<String> split() {
return getParts().iterator();
}
/** Splits path into components in reverse, excluding separators and empty strings. */
public Iterator<String> splitReverse() {
return Lists.reverse(getParts()).iterator();
}
@Override
public boolean equals(Object other) {
return this == other || other instanceof UnixPath && path.equals(((UnixPath) other).path);
}
@Override
public int hashCode() {
return path.hashCode();
}
/** Returns path as a string. */
@Override
public String toString() {
return path;
}
@Override
public int length() {
return path.length();
}
@Override
public char charAt(int index) {
return path.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return path.subSequence(start, end);
}
/** Returns {@code true} if this path is an empty string. */
public boolean isEmpty() {
return path.isEmpty();
}
/** Returns list of path components, excluding slashes. */
private List<String> getParts() {
List<String> result = lazyStringParts;
return result != null
? result
: (lazyStringParts =
path.isEmpty() || isRoot() ? Collections.<String>emptyList() : createParts());
}
private List<String> createParts() {
if (permitEmptyComponents) {
return SPLITTER_PERMIT_EMPTY_COMPONENTS.splitToList(
path.charAt(0) == SEPARATOR ? path.substring(1) : path);
} else {
return SPLITTER.splitToList(path);
}
}
}