commit: 9c34d08d7a175851060e8211c5b17184efb21e08
parent 137bc7e7ae964343170e4a2b4485c2fc979795a4
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Mon, 5 Apr 2021 05:21:41 +0200
bin/basename: New
Diffstat:
6 files changed, 95 insertions(+), 2 deletions(-)
diff --git a/README b/README
@@ -9,6 +9,8 @@ This is my utils which lives in my home PATH (~/.local/bin).
# Programs and what they do
+When they have the name of a POSIX tool they are intended to behave closely to the specification, some liberties are taken to avoid reimplementing libc functions that only differ slightly.
+
## argc
Prints number of arguments given.
diff --git a/bin/Makefile.config b/bin/Makefile.config
@@ -1,2 +1,2 @@
-EXE = args date echo lolcat mdate pwd range sizeof xcd
-MAN1 = date.1 lolcat.1
+EXE = args basename date echo lolcat mdate pwd range sizeof xcd
+MAN1 = basename.1 date.1 lolcat.1
diff --git a/bin/basename.1 b/bin/basename.1
@@ -0,0 +1,36 @@
+.Dd 2021-04-05
+.Dt BASENAME 1
+.Os
+.Sh NAME
+.Nm basename
+.Nd return last path compoment of a pathname
+.Sh SYNOPSIS
+.Nm
+.Op Ar string
+.Op Ar suffix
+.Sh DESCRIPTION
+When
+.Ar string
+isn't given
+.Dq \&.
+is returned.
+Otherwise it gives the last path compoment of
+.Ar string
+with removing the last part matching
+.Ar suffix
+when applicable.
+.Sh EXIT STATUS
+.Ex -std
+.Sh SEE ALSO
+.Xr basename 3
+.Sh STANDARDS
+.Nm
+is close but not compliant with the
+.St -p1003.1-2008
+specification as it uses
+.Xr basename 3
+directly instead of extracting the non-directory portion of
+.Ar string
+with it's own algorithm.
+.Sh AUTHORS
+.An Haelwenn (lanodan) Monnier Aq Mt contact@hacktivis.me
diff --git a/bin/basename.c b/bin/basename.c
@@ -0,0 +1,38 @@
+#include <libgen.h> // basename()
+#include <stdio.h> // fputs(), puts()
+#include <string.h> // strlen(), strcmp()
+
+char *suffix_basename(char *name, char *suffix)
+{
+ char *string = basename(name);
+
+ size_t suflen = suffix ? strlen(suffix) : 0;
+ size_t len = strlen(string);
+
+ if(suflen < len && strcmp(&string[len - suflen], suffix) == 0)
+ {
+ string[len - suflen] = '\0';
+ }
+
+ return string;
+}
+
+int main(int argc, char *argv[])
+{
+ switch(argc) {
+ case 1:
+ puts(".");
+ break;
+ case 2:
+ puts(basename(argv[1]));
+ break;
+ case 3:
+ puts(suffix_basename(argv[1], argv[2]));
+ break;
+ default:
+ fputs("usage: basename string [suffix]", stderr);
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/test-bin/Makefile b/test-bin/Makefile
@@ -1,2 +1,3 @@
test:
./xcd.t
+ ./basename.t
diff --git a/test-bin/basename.t b/test-bin/basename.t
@@ -0,0 +1,16 @@
+#!/bin/sh
+failed=0
+path=../bin/basename
+status() {
+ if [[ $2 -eq 0 ]]; then
+ echo "OK: ${1}"
+ else
+ echo "FAILED: ${1}"
+ failed=1
+ fi
+}
+[[ "$(${path})" == "." ]] ; status "no args" $?
+[[ "$(${path} /usr/bin)" == "bin" ]] ; status "/usr/bin" $?
+[[ "$(${path} /usr/bin-test -test)" == "bin" ]] ; status "/usr/bin-test -test" $?
+
+exit $failed