compat/basename: make basename() conform to POSIX
[git] / compat / basename.c
1 #include "../git-compat-util.h"
2
3 /* Adapted from libiberty's basename.c.  */
4 char *gitbasename (char *path)
5 {
6         const char *base;
7
8         if (path)
9                 skip_dos_drive_prefix(&path);
10
11         if (!path || !*path)
12                 return ".";
13
14         for (base = path; *path; path++) {
15                 if (!is_dir_sep(*path))
16                         continue;
17                 do {
18                         path++;
19                 } while (is_dir_sep(*path));
20                 if (*path)
21                         base = path;
22                 else
23                         while (--path != base && is_dir_sep(*path))
24                                 *path = '\0';
25         }
26         return (char *)base;
27 }