From 4fcc86b07db26da17f17af0fd777cab78fcaaf4c Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Thu, 19 Feb 2009 20:10:49 +0100 Subject: 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: strip_path_suffix("C:\\msysgit/\\libexec\\git-core", "libexec///git-core", &prefix) will set prefix to "C:\\msysgit" and return 0. Signed-off-by: Johannes Schindelin Acked-by: Johannes Sixt Signed-off-by: Junio C Hamano --- path.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'path.c') diff --git a/path.c b/path.c index 4b9107fed10..e332b504a6b 100644 --- a/path.c +++ b/path.c @@ -499,3 +499,39 @@ 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; +} + +/* + * If path ends with suffix (complete path components), returns the + * part before suffix (sans trailing directory separators). + * Otherwise returns NULL. + */ +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)); +} -- cgit v1.2.3