From 51c8f38fbc3ed665f91f2c1cca7cf183c64124fa Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Wed, 6 Jan 2016 15:54:36 +0100 Subject: [PATCH] compat/basename: make basename() conform to POSIX According to POSIX, basename("/path/") should return "path", not "path/". Likewise, basename(NULL) and basename("abc") should both return ".". Signed-off-by: Johannes Schindelin --- compat/basename.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/compat/basename.c b/compat/basename.c index 9f00421a26..0f1b0b0930 100644 --- a/compat/basename.c +++ b/compat/basename.c @@ -4,10 +4,24 @@ char *gitbasename (char *path) { const char *base; - skip_dos_drive_prefix(&path); + + if (path) + skip_dos_drive_prefix(&path); + + if (!path || !*path) + return "."; + for (base = path; *path; path++) { - if (is_dir_sep(*path)) - base = path + 1; + if (!is_dir_sep(*path)) + continue; + do { + path++; + } while (is_dir_sep(*path)); + if (*path) + base = path; + else + while (--path != base && is_dir_sep(*path)) + *path = '\0'; } return (char *)base; }