relative_path should honor dos-drive-prefix
authorJiang Xin <worldhello.net@gmail.com>
Mon, 14 Oct 2013 02:29:39 +0000 (10:29 +0800)
committerJonathan Nieder <jrnieder@gmail.com>
Mon, 14 Oct 2013 14:00:26 +0000 (07:00 -0700)
Tvangeste found that the "relative_path" function could not work
properly on Windows if "in" and "prefix" have DOS drive prefix
(such as "C:/windows"). ($gmane/234434)

E.g., When execute: test-path-utils relative_path "C:/a/b" "D:/x/y",
should return "C:/a/b", but returns "../../C:/a/b", which is wrong.

So make relative_path honor DOS drive prefix, and add test cases
for it in t0060.

Reported-by: Tvangeste <i.4m.l33t@yandex.ru>
Helped-by: Johannes Sixt <j6t@kdbg.org>
Signed-off-by: Jiang Xin <worldhello.net@gmail.com>
Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
path.c
t/t0060-path-utils.sh
diff --git a/path.c b/path.c
index 7f3324aeea8050c082f9bb52d769301cdede4805..0c16dc5fdb2153ba984d05cb5bfb23fd16a8f82d 100644 (file)
--- a/path.c
+++ b/path.c
@@ -441,6 +441,16 @@ int adjust_shared_perm(const char *path)
        return 0;
 }
 
+static int have_same_root(const char *path1, const char *path2)
+{
+       int is_abs1, is_abs2;
+
+       is_abs1 = is_absolute_path(path1);
+       is_abs2 = is_absolute_path(path2);
+       return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
+              (!is_abs1 && !is_abs2);
+}
+
 /*
  * Give path as relative to prefix.
  *
@@ -461,6 +471,16 @@ const char *relative_path(const char *in, const char *prefix,
        else if (!prefix_len)
                return in;
 
+       if (have_same_root(in, prefix)) {
+               /* bypass dos_drive, for "c:" is identical to "C:" */
+               if (has_dos_drive_prefix(in)) {
+                       i = 2;
+                       j = 2;
+               }
+       } else {
+               return in;
+       }
+
        while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
                if (is_dir_sep(prefix[i])) {
                        while (is_dir_sep(prefix[i]))
index 92976e0402ff5cd017accc604243a2a50b54bc29..40dfa2df6ebaa7c459ad2d440242bc028dc6f59e 100755 (executable)
@@ -210,6 +210,10 @@ relative_path foo/a/b/             foo/a/b         ./
 relative_path foo/a            foo/a/b         ../
 relative_path foo/x/y          foo/a/b         ../../x/y
 relative_path foo/a/c          foo/a/b         ../c
+relative_path foo/a/b          /foo/x/y        foo/a/b
+relative_path /foo/a/b         foo/x/y         /foo/a/b
+relative_path d:/a/b           D:/a/c          ../b            MINGW
+relative_path C:/a/b           D:/a/c          C:/a/b          MINGW
 relative_path foo/a/b          "<empty>"       foo/a/b
 relative_path foo/a/b          "<null>"        foo/a/b
 relative_path "<empty>"                /foo/a/b        ./