Skip to content

Commit

Permalink
3Path: Implement 'normalize()'.
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel Hekman authored and steve-todorov committed Jul 26, 2023
1 parent ba86f91 commit ecc11bd
Showing 1 changed file with 74 additions and 1 deletion.
75 changes: 74 additions & 1 deletion src/main/java/org/carlspring/cloud/storage/s3fs/S3Path.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
Expand Down Expand Up @@ -433,10 +436,80 @@ public boolean endsWith(String other)
return this.endsWith(new S3Path(this.fileSystem, other));
}

// Inspired by "JimfsPath.isNormal()"
@Override
public Path normalize()
{
return this;
List<String> pathParts = uriToList();
if (isNormal(pathParts))
return this;

Deque<String> newPathParts = new ArrayDeque<>();
for (String pathPart : pathParts)
{
if (pathPart.equals(".."))
{
String lastPathPart = newPathParts.peekLast();
if (lastPathPart != null && !lastPathPart.equals(".."))
{
newPathParts.removeLast();
}
else if (!isAbsolute())
{
// if there's a root and we have an extra ".." that would go
// up above the root, ignore it
newPathParts.add(pathPart);
}
}
else if (!pathPart.equals("."))
{
newPathParts.add(pathPart);
}
}
StringBuilder pathBuilder = new StringBuilder();
if (this.isAbsolute())
{
pathBuilder.append(PATH_SEPARATOR).append(this.fileStore.name()).append(PATH_SEPARATOR);
}
pathBuilder.append(Joiner.on(PATH_SEPARATOR).join(newPathParts));
if (newPathParts.size() > 0 && uri.endsWith(PATH_SEPARATOR))
{
pathBuilder.append(PATH_SEPARATOR);
}
return new S3Path(this.fileSystem, pathBuilder.toString());
}

// Inspired by "JimfsPath.isNormal()"
private boolean isNormal(List<String> pathParts)
{
if (getNameCount() == 0 || getNameCount() == 1 && !isAbsolute())
{
return true;
}
boolean foundNonParentName = isAbsolute(); // if there's a root, the
// path doesn't start with ..
boolean normal = true;
for (String pathPart : pathParts)
{
if (pathPart.equals(".."))
{
if (foundNonParentName)
{
normal = false;
break;
}
}
else
{
if (pathPart.equals("."))
{
normal = false;
break;
}
foundNonParentName = true;
}
}
return normal;
}

@Override
Expand Down

0 comments on commit ecc11bd

Please sign in to comment.