Skip to content

Commit 3f4ae4a

Browse files
jacob-kellergitster
authored andcommitted
prefix_path: support prefixes not ending in trailing slash
The prefix_path_gently() -- and its wrapper prefix_path() -- function normalizes the provided path and optionally adds the provided prefix to relative paths. If the prefix does not end in a trailing slash, the function will combine the last component of the prefix with the first component of the relative path. This is unlikely to produce a desirable result. Teach prefix_path_gently() to check if the prefix ends in a slash. If it does not, then insert a slash between the prefix and the path. Take care to avoid inserting a slash if the prefix is empty. Add test cases to cover the relative path behavior, which was previously untested. Signed-off-by: Jacob Keller <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 8613c2b commit 3f4ae4a

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

setup.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,9 @@ char *prefix_path_gently(const char *prefix, int len,
139139
return NULL;
140140
}
141141
} else {
142-
sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
142+
sanitized = xstrfmt("%.*s%s%s", len, len ? prefix : "",
143+
!len || prefix[len - 1] == '/' ? "" : "/",
144+
path);
143145
if (remaining_prefix)
144146
*remaining_prefix = len;
145147
if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {

t/t0060-path-utils.sh

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,24 @@ test_expect_success SYMLINKS 'prefix_path works with absolute path to a symlink
307307
test_cmp expect actual
308308
'
309309

310+
test_expect_success 'prefix_path works with relative path' '
311+
echo "prefix/a" >expect &&
312+
test-tool path-utils prefix_path "prefix/" "a" >actual &&
313+
test_cmp expect actual
314+
'
315+
316+
test_expect_success 'prefix_path works with relative path and prefix not ending in /' '
317+
echo "prefix/a" >expect &&
318+
test-tool path-utils prefix_path "prefix" "a" >actual &&
319+
test_cmp expect actual
320+
'
321+
322+
test_expect_success 'prefix_path works with relative path and empty prefix' '
323+
echo "a" >expect &&
324+
test-tool path-utils prefix_path "" "a" >actual &&
325+
test_cmp expect actual
326+
'
327+
310328
relative_path /foo/a/b/c/ /foo/a/b/ c/
311329
relative_path /foo/a/b/c/ /foo/a/b c/
312330
relative_path /foo/a//b//c/ ///foo/a/b// c/ POSIX

0 commit comments

Comments
 (0)