compat/basename: make basename() conform to POSIX
authorJohannes Schindelin <johannes.schindelin@gmx.de>
Tue, 12 Jan 2016 07:57:30 +0000 (08:57 +0100)
committerJunio C Hamano <gitster@pobox.com>
Tue, 12 Jan 2016 18:40:27 +0000 (10:40 -0800)
According to POSIX, basename("/path/") should return "path", not
"path/". Likewise, basename(NULL) and basename("") should both
return "." to conform.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
compat/basename.c
index 9f00421a26c306dbe5e40895594869f21c8405f7..0f1b0b0930ebaaf1448ba6760addfc20635d2cce 100644 (file)
@@ -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;
 }