I've been looking at some of the other pending commands, And found a getopt
implementation from 2017 by AOSP.
Looking at the source code, it doesn't seem unclean, nor overly large (about
100 lines).
It does use getopt_long_only, a GNU extension of glibc, but musl has that so it
will work
on both glibc and musl. It is GNU compatible too, all test cases pass (even for
TEST_HOST).
There were a few things I changed (printf to xputsn/putchar/xprintf), and added
a link
to https://man7.org/linux/man-pages/man1/getopt.1.html, both in the attached
patch.
There doesn't seem like a good reason for this command to be in pending, are
the calls to
getopt_long_only a problem?
- Oliver Webb <aquahobby...@proton.me>
From 917485aec1d5093b708472f7ff82d165a3162a8c Mon Sep 17 00:00:00 2001
From: Oliver Webb <aquahobby...@proton.me>
Date: Wed, 28 Feb 2024 17:34:53 -0600
Subject: [PATCH] getopt.c: Formatting, printf -> xprintf/xputsn/putchar,
Referance link
---
toys/pending/getopt.c | 23 +++++++++++++----------
1 file changed, 13 insertions(+), 10 deletions(-)
diff --git a/toys/pending/getopt.c b/toys/pending/getopt.c
index 225db579..e6e239a5 100644
--- a/toys/pending/getopt.c
+++ b/toys/pending/getopt.c
@@ -1,6 +1,9 @@
/* getopt.c - Parse command-line options
*
* Copyright 2019 The Android Open Source Project
+ *
+ * See https://man7.org/linux/man-pages/man1/getopt.1.html
+ * No standard
USE_GETOPT(NEWTOY(getopt, "^a(alternative)n:(name)o:(options)l*(long)(longoptions)Tu", TOYFLAG_USR|TOYFLAG_BIN))
@@ -31,14 +34,14 @@ GLOBALS(
static void out(char *s)
{
- if (FLAG(u)) printf(" %s", s);
+ if (FLAG(u)) xprintf(" %s", s);
else {
- printf(" '");
+ xputsn(" '");
for (; *s; s++) {
- if (*s == '\'') printf("'\\''");
+ if (*s == '\'') xputsn("'\\''");
else putchar(*s);
}
- printf("'");
+ putchar('\'');
}
}
@@ -85,21 +88,21 @@ void getopt_main(void)
// BSD getopts don't honor argv[0] (for -n), so handle errors ourselves.
opterr = 0;
optind = 1;
- while ((ch = (FLAG(a)?getopt_long_only:getopt_long)(argc, argv, TT.o,
+ while ((ch = (FLAG(a) ? getopt_long_only : getopt_long)(argc, argv, TT.o,
lopts, &i)) != -1) {
if (ch == '?') {
fprintf(stderr, "%s: invalid option '%c'\n", argv[0], optopt);
toys.exitval = 1;
} else if (!ch) {
- printf(" --%s", lopts[i].name);
- if (lopts[i].has_arg) out(optarg ? optarg : "");
+ xprintf(" --%s", lopts[i].name);
+ if (lopts[i].has_arg) out(optarg ? : "");
} else {
- printf(" -%c", ch);
+ xprintf(" -%c", ch);
if (optarg) out(optarg);
}
}
- printf(" --");
+ xputsn(" --");
for (; optind<argc; optind++) out(argv[optind]);
- printf("\n");
+ putchar('\n');
}
--
2.44.0
_______________________________________________
Toybox mailing list
Toybox@lists.landley.net
http://lists.landley.net/listinfo.cgi/toybox-landley.net