diff src/org/tmatesoft/hg/util/Path.java @ 443:072b5f3ed0c8

Path to tell immediate parent-child relationship; more powerful scope impl; tests for both
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Fri, 04 May 2012 17:59:22 +0200
parents 12f668401613
children fedc54356091 49f0749307a0
line wrap: on
line diff
--- a/src/org/tmatesoft/hg/util/Path.java	Fri Apr 27 20:57:20 2012 +0200
+++ b/src/org/tmatesoft/hg/util/Path.java	Fri May 04 17:59:22 2012 +0200
@@ -118,11 +118,11 @@
 	}
 	
 	public enum CompareResult {
-		Same, Unrelated, Nested, Parent, /* perhaps, also ImmediateParent, DirectChild? */
+		Same, Unrelated, ImmediateChild, Nested, ImmediateParent, Parent /* +CommonParent ?*/
 	}
 	
-	/*
-	 * a/file and a/dir ?
+	/**
+	 * @return one of {@link CompareResult} constants to indicate relations between the paths 
 	 */
 	public CompareResult compareWith(Path another) {
 		if (another == null) {
@@ -131,14 +131,23 @@
 		if (another == this || (another.length() == length() && equals(another))) {
 			return CompareResult.Same;
 		}
-		if (path.startsWith(another.path)) {
-			return CompareResult.Nested;
+		// one of the parties can't be parent in parent/nested, the other may be either file or folder 
+		if (another.isDirectory() && path.startsWith(another.path)) {
+			return isOneSegmentDifference(path, another.path) ? CompareResult.ImmediateChild : CompareResult.Nested;
 		}
-		if (another.path.startsWith(path)) {
-			return CompareResult.Parent;
+		if (isDirectory() && another.path.startsWith(path)) {
+			return isOneSegmentDifference(another.path, path) ? CompareResult.ImmediateParent : CompareResult.Parent;
 		}
 		return CompareResult.Unrelated;
 	}
+	
+	// true if p1 is only one segment larger than p2
+	private static boolean isOneSegmentDifference(String p1, String p2) {
+		assert p1.startsWith(p2);
+		String p1Tail= p1.substring(p2.length());
+		int slashLoc = p1Tail.indexOf('/');
+		return slashLoc == -1 || slashLoc == p1Tail.length() - 1;
+	}
 
 	public static Path create(CharSequence path) {
 		if (path == null) {