[Toybox] [PATCH] basename: -s SUFFIX.

enh enh at google.com
Mon Nov 12 20:57:28 PST 2018


AOSP doesn't need -a specifically, but since it's needed for -s we may
as well accept it too.
---
 tests/basename.test   |  5 +++++
 toys/posix/basename.c | 33 ++++++++++++++++++++++++++-------
 2 files changed, 31 insertions(+), 7 deletions(-)

diff --git a/tests/basename.test b/tests/basename.test
index 25e5493..9fd570f 100755
--- a/tests/basename.test
+++ b/tests/basename.test
@@ -24,3 +24,8 @@ testcmd "invalid suffix" "isthisasuffix? suffix"
"isthisasuffix?\n" "" ""

 # Zero-length suffix
 testcmd "zero-length suffix" "a/b/c ''" "c\n" "" ""
+
+# -s.
+testcmd "-s" "-s .txt /a/b/c.txt" "c\n" "" ""
+testcmd "-s implies -a" "-s .txt /a/b/c.txt /a/b/d.txt" "c\nd\n" "" ""
+testcmd "-a" "-a /a/b/f1 /c/d/f2" "f1\nf2\n" "" ""
diff --git a/toys/posix/basename.c b/toys/posix/basename.c
index 0436bfe..11b9622 100644
--- a/toys/posix/basename.c
+++ b/toys/posix/basename.c
@@ -5,25 +5,44 @@
  * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html


-USE_BASENAME(NEWTOY(basename, "<1>2", TOYFLAG_USR|TOYFLAG_BIN))
+USE_BASENAME(NEWTOY(basename, "<1as:", TOYFLAG_USR|TOYFLAG_BIN))

 config BASENAME
   bool "basename"
   default y
   help
-    usage: basename string [suffix]
+    usage: basename [-a] [-s SUFFIX] NAME... | NAME [SUFFIX]

-    Return non-directory portion of a pathname removing suffix
+    Return non-directory portion of a pathname removing suffix.
+
+    -a All arguments are names.
+    -s SUFFIX Remove suffix (implies -a).
 */

+#define FOR_basename
 #include "toys.h"

+GLOBALS(
+  char *s;
+)
+
 void basename_main(void)
 {
-  char *base = basename(*toys.optargs), *suffix = toys.optargs[1];
+  char **arg;
+
+  if (toys.optflags&FLAG_s) toys.optflags |= FLAG_a;
+
+  if (!(toys.optflags&FLAG_a)) {
+    if (toys.optc > 2) error_exit("too many args");
+    TT.s = toys.optargs[1];
+    toys.optargs[1] = NULL;
+  }

-  // chop off the suffix if provided
-  if (suffix && *suffix && (suffix = strend(base, suffix))) *suffix = 0;
+  for (arg = toys.optargs; *arg; ++arg) {
+    char *base = basename(*arg), *p;

-  puts(base);
+    // Chop off the suffix if provided.
+    if (TT.s && *TT.s && (p = strend(base, TT.s))) *p = 0;
+    puts(base);
+  }
 }
-- 
2.19.1.930.g4563a0d9d0-goog
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 0001-basename-s-SUFFIX.patch
Type: text/x-patch
Size: 2426 bytes
Desc: not available
URL: <http://lists.landley.net/pipermail/toybox-landley.net/attachments/20181112/16266406/attachment.bin>


More information about the Toybox mailing list