Code

ignore duplicated slashes in make_relative_path()
authorJunio C Hamano <gitster@pobox.com>
Fri, 22 Jan 2010 03:05:19 +0000 (19:05 -0800)
committerJunio C Hamano <gitster@pobox.com>
Fri, 22 Jan 2010 23:34:56 +0000 (15:34 -0800)
The function takes two paths, an early part of abs is supposed to match
base; otherwise abs is not a path under base and the function returns the
full path of abs.  The caller can easily confuse the implementation by
giving duplicated and needless slashes in these path arguments.

Credit for test script, motivation and initial patch goes to Thomas Rast.
A follow-up fix (squashed) is by Hannes.

Signed-off-by: Junio C Hamano <gitster@pobox.com>
path.c
t/t1501-worktree.sh

diff --git a/path.c b/path.c
index 2ec950b27f1c3e4919ce7d1696360c5a49abb724..79aa104712364a8c18964feecd4c8079449a78cf 100644 (file)
--- a/path.c
+++ b/path.c
@@ -394,17 +394,38 @@ int set_shared_perm(const char *path, int mode)
 const char *make_relative_path(const char *abs, const char *base)
 {
        static char buf[PATH_MAX + 1];
-       int baselen;
-       if (!base)
-               return abs;
-       baselen = strlen(base);
-       if (prefixcmp(abs, base))
+       int i = 0, j = 0;
+
+       if (!base || !base[0])
                return abs;
-       if (abs[baselen] == '/')
-               baselen++;
-       else if (base[baselen - 1] != '/')
+       while (base[i]) {
+               if (is_dir_sep(base[i])) {
+                       if (!is_dir_sep(abs[j]))
+                               return abs;
+                       while (is_dir_sep(base[i]))
+                               i++;
+                       while (is_dir_sep(abs[j]))
+                               j++;
+                       continue;
+               } else if (abs[j] != base[i]) {
+                       return abs;
+               }
+               i++;
+               j++;
+       }
+       if (
+           /* "/foo" is a prefix of "/foo" */
+           abs[j] &&
+           /* "/foo" is not a prefix of "/foobar" */
+           !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
+          )
                return abs;
-       strcpy(buf, abs + baselen);
+       while (is_dir_sep(abs[j]))
+               j++;
+       if (!abs[j])
+               strcpy(buf, ".");
+       else
+               strcpy(buf, abs + j);
        return buf;
 }
 
index 74e6443664010196f2694304179917fdadc53c01..9df301211c7f03e4a9edb0ccb9b1a7a648f97d8c 100755 (executable)
@@ -189,4 +189,10 @@ test_expect_success 'absolute pathspec should fail gracefully' '
        )
 '
 
+test_expect_success 'make_relative_path handles double slashes in GIT_DIR' '
+       : > dummy_file
+       echo git --git-dir="$(pwd)//repo.git" --work-tree="$(pwd)" add dummy_file &&
+       git --git-dir="$(pwd)//repo.git" --work-tree="$(pwd)" add dummy_file
+'
+
 test_done