[PATCH] path: Add l_basename function

Denis Kenzior <[email protected]> Tue, 28 May 2024 08:25:40 -0700
Newsgroups dev.linux.lists.ell
Message-ID <[email protected]>
Many ell based projects use the GNU version (obtained using #define
_GNU_SOURCE).  Unlike the POSIX version, this version does not modify
its arguments.  However, some libc implementations such as musl, only
provide the POSIX implementation.  Implement a version of basename in
ell.
---
 ell/ell.sym |  1 +
 ell/path.c  | 19 +++++++++++++++++++
 ell/path.h  |  2 ++
 3 files changed, 22 insertions(+)

diff --git a/ell/ell.sym b/ell/ell.sym
index 28b55d3..803906c 100644
--- a/ell/ell.sym
+++ b/ell/ell.sym
@@ -434,6 +434,7 @@ global:
 	l_netlink_unregister;
 	l_netlink_set_debug;
 	/* path */
+	l_basename;
 	l_path_find;
 	l_path_get_mtime;
 	l_path_next;
diff --git a/ell/path.c b/ell/path.c
index 8004c2e..e5b7bcb 100644
--- a/ell/path.c
+++ b/ell/path.c
@@ -173,3 +173,22 @@ LIB_EXPORT int l_path_touch(const char *path)
 
 	return -errno;
 }
+
+/**
+ * l_basename:
+ * @path: The path to find the base name of
+ *
+ * This function operates similarly to the glibc version of basename.  This
+ * version never modifies its argument and returns the contents in path after
+ * the last '/' character.  Note that this will result in an empty string being
+ * returned when @path ends in a trailing slash.
+ */
+LIB_EXPORT const char *l_basename(const char *path)
+{
+	const char *p = strrchr(path, '/');
+
+	if (p)
+		return p + 1;
+
+	return path;
+}
diff --git a/ell/path.h b/ell/path.h
index 1f151de..5046dcd 100644
--- a/ell/path.h
+++ b/ell/path.h
@@ -17,6 +17,8 @@ char *l_path_find(const char *basename, const char *path_str, int mode);
 uint64_t l_path_get_mtime(const char *path);
 int l_path_touch(const char *path);
 
+const char *l_basename(const char *path);
+
 #ifdef __cplusplus
 }
 #endif
-- 
2.45.1