Browse Source

fix: PathUtils#common shouldn't use absolute paths

Ranides Atterwim 4 năm trước cách đây
mục cha
commit
339735ace1

+ 21 - 5
assira.core/src/main/java/net/ranides/assira/io/PathUtils.java

@@ -153,7 +153,7 @@ public final class PathUtils {
     }
 
     public static Path common(Path a, Path b) {
-        return cwd().relativize(common0(a,b));
+        return common0(a,b);
     }
 
 
@@ -161,12 +161,19 @@ public final class PathUtils {
         if(values.isEmpty()) {
             return cwd();
         }
-        return cwd().relativize(values.stream().reduce(values.iterator().next(), PathUtils::common0));
+        return values.stream().reduce(values.iterator().next(), PathUtils::common0);
     }
 
     private static Path common0(Path a, Path b) {
-        Path na = PathUtils.normalize(a);
-        Path nb = PathUtils.normalize(b);
+        Path na = a.normalize();
+        Path nb = b.normalize();
+
+        if(na.isAbsolute() ^ nb.isAbsolute()) {
+            return Paths.get("");
+        }
+        if(na.isAbsolute() && !na.getRoot().equals(nb.getRoot())) {
+            return Paths.get("");
+        }
 
         int i = 0;
         int n = Math.min(na.getNameCount(), nb.getNameCount());
@@ -174,7 +181,16 @@ public final class PathUtils {
         while(i<n && na.getName(i).equals(nb.getName(i))) {
             i++;
         }
-        return na.getRoot().resolve(na.subpath(0,i));
+
+        if(i == 0) {
+            return Paths.get("");
+        }
+
+        if(na.isAbsolute()) {
+            return na.getRoot().resolve(na.subpath(0,i));
+        } else {
+            return na.subpath(0, i);
+        }
     }
 
 }

+ 8 - 0
assira.core/src/test/java/net/ranides/assira/io/PathUtilsTest.java

@@ -252,6 +252,14 @@ public class PathUtilsTest {
 
         assertEquals("foo\\here", home.toString());
         assertEquals("dir\\file1", home.relativize(Paths.get("foo/here/dir/file1")).toString());
+
+        Path a = PathUtils.common(Arrays.asList(Paths.get("d:\\where\\directory\\first"), Paths.get("q:\\where\\directory\\second"), Paths.get("d:\\where\\directory\\third")));
+        Path b = PathUtils.common(Arrays.asList(Paths.get("d:\\where\\directory\\first"), Paths.get("d:\\where\\directory\\second"), Paths.get("d:\\where\\directory\\third")));
+        Path c = PathUtils.common(Arrays.asList(Paths.get("first"), Paths.get("second"), Paths.get("third")));
+
+        assertEquals("", a.toString());
+        assertEquals("d:\\where\\directory", b.toString());
+        assertEquals("", c.toString());
     }
 
     private static Path pce(String path, String ext) {