ignore duplicated slashes in make_relative_path()
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>
Junio C Hamano committed
Jan 21, 2010 at 19:05 UTC
288123f01cb1b835edbf6e2e188159c2ff858aca
2 files changed
+36
-9
path.c
+30
-9
@@ -394,17 +394,38 @@ int set_shared_perm(const char *path, int mode)
394
const char *make_relative_path(const char *abs, const char *base)
395
{
396
static char buf[PATH_MAX + 1];
397
- int baselen;
398
- if (!base)
399
- return abs;
400
- baselen = strlen(base);
401
- if (prefixcmp(abs, base))
397
+ int i = 0, j = 0;
398
+
399
+ if (!base || !base[0])
400
return abs;
403
- if (abs[baselen] == '/')
404
- baselen++;
405
- else if (base[baselen - 1] != '/')
401
+ while (base[i]) {
402
+ if (is_dir_sep(base[i])) {
403
+ if (!is_dir_sep(abs[j]))
404
+ return abs;
405
+ while (is_dir_sep(base[i]))
406
+ i++;
407
+ while (is_dir_sep(abs[j]))
408
+ j++;
409
+ continue;
410
+ } else if (abs[j] != base[i]) {
411
+ return abs;
412
+ }
413
+ i++;
414
+ j++;
415
+ }
416
+ if (
417
+ /* "/foo" is a prefix of "/foo" */
418
+ abs[j] &&
419
+ /* "/foo" is not a prefix of "/foobar" */
420
+ !is_dir_sep(base[i-1]) && !is_dir_sep(abs[j])
421
+ )
422
return abs;
407
- strcpy(buf, abs + baselen);
423
+ while (is_dir_sep(abs[j]))
424
+ j++;
425
+ if (!abs[j])
426
+ strcpy(buf, ".");
427
+ else
428
+ strcpy(buf, abs + j);
429
return buf;
430
}
431
t/t1501-worktree.sh
+6
@@ -189,4 +189,10 @@ test_expect_success 'absolute pathspec should fail gracefully' '
189
)
190
'
191
192
+test_expect_success 'make_relative_path handles double slashes in GIT_DIR' '
193
+ : > dummy_file
194
+ echo git --git-dir="$(pwd)//repo.git" --work-tree="$(pwd)" add dummy_file &&
195
+ git --git-dir="$(pwd)//repo.git" --work-tree="$(pwd)" add dummy_file
196
+'
197
+
198
test_done