Introduce the function strip_path_suffix()

The function strip_path_suffix() will try to strip a given suffix from
a given path.  The suffix must start at a directory boundary (i.e. "core"
is not a path suffix of "libexec/git-core", but "git-core" is).

Arbitrary runs of directory separators ("slashes") are assumed identical.

Example:

	prefix = strip_path_suffix("C:\\msysgit/\\libexec\\git-core",
			"libexec///git-core");

will set prefix to "C:\\msysgit".

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
This commit is contained in:
Johannes Schindelin
2009-02-18 15:32:55 +01:00
parent 3cb35a31b0
commit b824fc9cef
4 changed files with 42 additions and 0 deletions

View File

@@ -629,6 +629,7 @@ const char *make_nonrelative_path(const char *path);
const char *make_relative_path(const char *abs, const char *base);
int normalize_absolute_path(char *buf, const char *path);
int longest_ancestor_length(const char *path, const char *prefix_list);
char *strip_path_suffix(const char *path, const char *suffix);
/* Read and unpack a sha1 file into memory, write memory to a sha1 file */
extern int sha1_object_info(const unsigned char *, unsigned long *);

32
path.c
View File

@@ -457,3 +457,35 @@ int longest_ancestor_length(const char *path, const char *prefix_list)
return max_len;
}
/* strip arbitrary amount of directory separators at end of path */
static inline int chomp_trailing_dir_sep(const char *path, int len)
{
while (len && is_dir_sep(path[len - 1]))
len--;
return len;
}
/* sets prefix if the suffix matches */
char *strip_path_suffix(const char *path, const char *suffix)
{
int path_len = strlen(path), suffix_len = strlen(suffix);
while (suffix_len) {
if (!path_len)
return NULL;
if (is_dir_sep(path[path_len - 1])) {
if (!is_dir_sep(suffix[suffix_len - 1]))
return NULL;
path_len = chomp_trailing_dir_sep(path, path_len);
suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
}
else if (path[--path_len] != suffix[--suffix_len])
return NULL;
}
if (path_len && !is_dir_sep(path[path_len - 1]))
return NULL;
return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
}

View File

@@ -84,4 +84,8 @@ ancestor /foo/bar :://foo/.:: 4
ancestor /foo/bar //foo/./::/bar 4
ancestor /foo/bar ::/bar -1
test_expect_success 'strip_path_suffix' '
test c:/msysgit = $(test-path-utils strip_path_suffix \
c:/msysgit/libexec//git-core libexec/git-core)
'
test_done

View File

@@ -22,5 +22,10 @@ int main(int argc, char **argv)
printf("%d\n", len);
}
if (argc == 4 && !strcmp(argv[1], "strip_path_suffix")) {
char *prefix = strip_path_suffix(argv[2], argv[3]);
printf("%s\n", prefix ? prefix : "(null)");
}
return 0;
}