Skip to content

Instantly share code, notes, and snippets.

@searls
Created July 1, 2011 18:47
Show Gist options
  • Save searls/1059158 to your computer and use it in GitHub Desktop.
Save searls/1059158 to your computer and use it in GitHub Desktop.
package com.github.searls.jasmine.io;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
public class RelativizesFilePathsTest {
private RelativizesFilePaths subject = new RelativizesFilePaths();
private File from;
private File to;
@Test
public void resolvesWithinDir() throws IOException {
from = new File("/panda/");
to = new File("/panda/pants.txt");
String result = subject.relativize(from,to);
assertThat(result,is("pants.txt"));
}
@Test
public void resolvesSubDir() throws IOException {
from = new File("/panda/");
to = new File("/panda/target/jasmine/");
String result = subject.relativize(from,to);
assertThat(result,is("target/jasmine"));
}
@Test
public void resolvesDeepChild() throws IOException {
from = new File("/Volumes/blah/Users/justin/code/workspaces/jasmine_maven/jasmine-maven-plugin/src/test/resources/examples/jasmine-webapp-coffee/target/jasmine");
to = new File("/Volumes/blah/Users/justin/code/workspaces/jasmine_maven/jasmine-maven-plugin/src/test/resources/examples/jasmine-webapp-coffee/src/test/javascript/fun-spec.js");
String result = subject.relativize(from,to);
assertThat(result,is("../../src/test/javascript/fun-spec.js"));
}
}
package com.github.searls.jasmine.io;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import static org.apache.commons.lang.StringUtils.*;
@SuppressWarnings("unused")
public class RelativizesFilePaths {
public String relativize(File from, File to) throws IOException {
String fromPath = from.getCanonicalPath();
String toPath = to.getCanonicalPath();
String root = getCommonPrefix(new String[] { fromPath, toPath });
StringBuffer result = new StringBuffer();
if (fromPathIsNotADirectAncestor(fromPath, root)) {
for (String dir : divergentDirectories(root, fromPath)) {
result.append("..").append(File.separator);
}
}
result.append(pathAfterRoot(toPath, root));
return trimLeadingSlashIfNecessary(result);
}
private boolean fromPathIsNotADirectAncestor(String fromPath, String root) {
return !StringUtils.equals(root, fromPath);
}
private String[] divergentDirectories(String root, String fullPath) {
return pathAfterRoot(fullPath, root).split(File.separator);
}
private String pathAfterRoot(String path, String root) {
return substringAfterLast(path, root);
}
private String trimLeadingSlashIfNecessary(StringBuffer result) {
return removeStart(result.toString(),File.separator);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment