public inbox for u-boot@lists.denx.de
 help / color / mirror / Atom feed
From: Sean Anderson <seanga2@gmail.com>
To: u-boot@lists.denx.de
Subject: [PATCH 13/18] lib: Add getopt
Date: Tue,  6 Oct 2020 15:16:05 -0400	[thread overview]
Message-ID: <20201006191610.761899-14-seanga2@gmail.com> (raw)
In-Reply-To: <20201006191610.761899-1-seanga2@gmail.com>

Some commands can get very unweildy if they have too many positional
arguments. Adding options makes them easier to read, remember, and
understand.

This implementation of getopt has been taken from barebox, which has had
option support for quite a while. I have made a few modifications to their
version, such as the removal of opterr in favor of a separate getopt_silent
function. In addition, I have moved all global variables into struct
getopt_context.

The getopt from barebox also re-orders the arguments passed to it so that
non-options are placed last. This allows users to specify options anywhere.
For example, `ls -l foo/ -R` would be re-ordered to `ls -l -R foo/` as
getopt parsed the options. However, this feature conflicts with the const
argv in cmd_tbl->cmd. This was originally added in 54841ab50c ("Make sure
that argv[] argument pointers are not modified."). The reason stated in
that commit is that hush requires argv to stay unmodified. Has this
situation changed? Barebox also uses hush, and does not have this problem.
Perhaps we could use their fix?

I have assigned maintenance of getopt to Simon Glass, as it is currently
only used by the log command. I would also be fine maintaining it.

Signed-off-by: Sean Anderson <seanga2@gmail.com>
---

 MAINTAINERS        |   1 +
 doc/api/getopt.rst |   8 +++
 doc/api/index.rst  |   1 +
 include/getopt.h   | 105 +++++++++++++++++++++++++++++++++++++
 lib/Kconfig        |   5 ++
 lib/Makefile       |   1 +
 lib/getopt.c       | 125 +++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 246 insertions(+)
 create mode 100644 doc/api/getopt.rst
 create mode 100644 include/getopt.h
 create mode 100644 lib/getopt.c

diff --git a/MAINTAINERS b/MAINTAINERS
index 85babd1908..45ef4321d7 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -747,6 +747,7 @@ T:	git https://gitlab.denx.de/u-boot/u-boot.git
 F:	common/log*
 F:	cmd/log.c
 F:	doc/develop/logging.rst
+F:	lib/getopt.c
 F:	test/log/
 F:	test/py/tests/test_log.py
 
diff --git a/doc/api/getopt.rst b/doc/api/getopt.rst
new file mode 100644
index 0000000000..773f79aeb6
--- /dev/null
+++ b/doc/api/getopt.rst
@@ -0,0 +1,8 @@
+.. SPDX-License-Identifier: GPL-2.0+
+.. Copyright (C) 2020 Sean Anderson <seanga2@gmail.com>
+
+Option Parsing
+==============
+
+.. kernel-doc:: include/getopt.h
+   :internal:
diff --git a/doc/api/index.rst b/doc/api/index.rst
index b7eb5725f2..6c849c50b6 100644
--- a/doc/api/index.rst
+++ b/doc/api/index.rst
@@ -8,6 +8,7 @@ U-Boot API documentation
 
    dfu
    efi
+   getopt
    linker_lists
    rng
    serial
diff --git a/include/getopt.h b/include/getopt.h
new file mode 100644
index 0000000000..186a3c231e
--- /dev/null
+++ b/include/getopt.h
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * getopt.h - a simple getopt(3) implementation.
+ *
+ * Copyright (C) 2020 Sean Anderson <seanga2@gmail.com>
+ * Copyright (c) 2007 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
+ */
+
+#ifndef __GETOPT_H
+#define __GETOPT_H
+
+/**
+ * struct getopt_state - Saved state across getopt() calls
+ */
+struct getopt_state {
+	/** @optind: Index of the next unparsed argument of argv */
+	int optind;
+	/* private: */
+	/** @optindex: Index within the current argument */
+	int optindex;
+	union {
+		/* public: */
+		/** @optopt: Option being parsed when an error occurs */
+		int optopt;
+		/** @optarg: The argument to an option, NULL if there is none */
+		char *optarg;
+	/* private: */
+	};
+};
+
+/**
+ * getopt_init_state() - Initialize a &struct getopt_state
+ * @gs: The state to initialize
+ *
+ * This must be called before using @gs with getopt().
+ */
+void getopt_init_state(struct getopt_state *gs);
+
+int __getopt(struct getopt_state *gs, int argc, char *const argv[],
+	     const char *optstring, bool silent);
+
+/**
+ * getopt() - Parse short command-line options
+ * @gs: Internal state and out-of-band return arguments. This must be
+ *      initialized with getopt_init_context() beforehand.
+ * @argc: Number of arguments
+ * @argv: Argument list
+ * @optstring: Option specification, as described below
+ *
+ * getopt() parses short options. Short options are single characters. They may
+ * be followed by a required argument or an optional argument. Arguments to
+ * options may occur in the same argument as an option (like ``-loptarg``), or
+ * in the following argument (like ``-l optarg``). An argument containing
+ * options begins with a ``-``. If an option expects no arguments, then it may
+ * be immediately followed by another option (like ``ls -alR``).
+ *
+ * @optstring is a list of accepted options. If an option is followed by ``:``
+ * in @optstring, then it expects a mandatory argument. If an option is followed
+ * by ``::`` in @optstring, it expects an optional argument. @gs.optarg points
+ * to the argument, if one is parsed.
+ *
+ * getopt() stops parsing options when it encounters the first non-option
+ * argument, when it encounters the argument ``--``, or when it runs out of
+ * arguments. For example, in ``ls -l foo -R``, option parsing will stop when
+ * getopt() encounters ``foo``, if ``l`` does not expect an argument. However,
+ * the whole list of arguments would be parsed if ``l`` expects an argument.
+ *
+ * For further information, refer to the getopt(3) man page.
+ *
+ * Return:
+ * * An option character if an option is found. @gs.optarg is set to the
+ *   argument if there is one, otherwise it is set to ``NULL``.
+ * * ``-1`` if there are no more options, if a non-option argument is
+ *   encountered, or if an ``--`` argument is encountered.
+ * * ``'?'`` if we encounter an option not in @optstring. @gs.optopt is set to
+ *   the unknown option.
+ * * ``':'`` if an argument is required, but no argument follows the
+ *   option. @gs.optopt is set to the option missing its argument.
+ *
+ * @gs.optind is always set to the index of the next unparsed argument in @argv.
+ */
+static inline int getopt(struct getopt_state *gs, int argc,
+			 char *const argv[], const char *optstring)
+{
+	return __getopt(gs, argc, argv, optstring, false);
+}
+
+/**
+ * getopt_silent() - Parse short command-line options
+ * @gs: Internal state and out-of-band return arguments. This must be
+ *      initialized with getopt_init_context() beforehand.
+ * @argc: Number of arguments
+ * @argv: Argument list
+ * @optstring: Option specification
+ *
+ * Arguments and return values are the same as getopt(), except no error
+ * messages are printed.
+ */
+static inline int getopt_silent(struct getopt_state *gs, int argc,
+				char *const argv[], const char *optstring)
+{
+	return __getopt(gs, argc, argv, optstring, true);
+}
+
+#endif /* __GETOPT_H */
diff --git a/lib/Kconfig b/lib/Kconfig
index 8efb154f73..a3346eee04 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -542,6 +542,11 @@ config HEXDUMP
 	help
 	  This enables functions for printing dumps of binary data.
 
+config GETOPT
+	bool "Enable getopt"
+	help
+	  This enables functions for parsing command-line options.
+
 config OF_LIBFDT
 	bool "Enable the FDT library"
 	default y if OF_CONTROL
diff --git a/lib/Makefile b/lib/Makefile
index 0cd7bea282..7c7fb9aae7 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -106,6 +106,7 @@ obj-y += string.o
 obj-y += tables_csum.o
 obj-y += time.o
 obj-y += hexdump.o
+obj-$(CONFIG_GETOPT) += getopt.o
 obj-$(CONFIG_TRACE) += trace.o
 obj-$(CONFIG_LIB_UUID) += uuid.o
 obj-$(CONFIG_LIB_RAND) += rand.o
diff --git a/lib/getopt.c b/lib/getopt.c
new file mode 100644
index 0000000000..7a4bb9c150
--- /dev/null
+++ b/lib/getopt.c
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * getopt.c - a simple getopt(3) implementation. See getopt.h for explanation.
+ *
+ * Copyright (C) 2020 Sean Anderson <seanga2@gmail.com>
+ * Copyright (c) 2007 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
+ */
+
+#define LOG_CATEGORY LOGC_CORE
+
+#include <common.h>
+#include <getopt.h>
+#include <log.h>
+
+void getopt_init_state(struct getopt_state *gs)
+{
+	gs->optind = 1;
+	gs->optindex = 1;
+}
+
+int __getopt(struct getopt_state *gs, int argc, char *const argv[],
+	     const char *optstring, bool silent)
+{
+	char curopt;   /* current option character */
+	const char *curoptp; /* pointer to the current option in optstring */
+
+	while (1) {
+		log_debug("optindex: %d optind: %d\n", gs->optindex,
+			  gs->optind);
+
+		/* `--` indicates the end of options */
+		if (gs->optindex == 1 && argv[gs->optind] &&
+		    !strcmp(argv[gs->optind], "--")) {
+			gs->optind++;
+			return -1;
+		}
+
+		/* Out of arguments */
+		if (gs->optind >= argc)
+			return -1;
+
+		/* Can't parse non-options */
+		if (*argv[gs->optind] != '-')
+			return -1;
+
+		/* We have found an option */
+		curopt = argv[gs->optind][gs->optindex];
+		if (curopt)
+			break;
+		/*
+		 * no more options in current argv[] element; try the next one
+		 */
+		gs->optind++;
+		gs->optindex = 1;
+	}
+
+	/* look up current option in optstring */
+	curoptp = strchr(optstring, curopt);
+
+	if (!curoptp) {
+		if (!silent)
+			printf("%s: invalid option -- %c\n", argv[0], curopt);
+		gs->optopt = curopt;
+		gs->optindex++;
+		return '?';
+	}
+
+	if (*(curoptp + 1) != ':') {
+		/* option with no argument. Just return it */
+		gs->optarg = NULL;
+		gs->optindex++;
+		return curopt;
+	}
+
+	if (*(curoptp + 1) && *(curoptp + 2) == ':') {
+		/* optional argument */
+		if (argv[gs->optind][gs->optindex + 1]) {
+			/* optional argument with directly following optarg */
+			gs->optarg = argv[gs->optind++] + gs->optindex + 1;
+			gs->optindex = 1;
+			return curopt;
+		}
+		if (gs->optind + 1 == argc) {
+			/* We are at the last argv[] element */
+			gs->optarg = NULL;
+			gs->optind++;
+			return curopt;
+		}
+		if (*argv[gs->optind + 1] != '-') {
+			/*
+			 * optional argument with optarg in next argv[] element
+			 */
+			gs->optind++;
+			gs->optarg = argv[gs->optind++];
+			gs->optindex = 1;
+			return curopt;
+		}
+
+		/* no optional argument found */
+		gs->optarg = NULL;
+		gs->optindex = 1;
+		gs->optind++;
+		return curopt;
+	}
+
+	if (argv[gs->optind][gs->optindex + 1]) {
+		/* required argument with directly following optarg */
+		gs->optarg = argv[gs->optind++] + gs->optindex + 1;
+		gs->optindex = 1;
+		return curopt;
+	}
+
+	gs->optind++;
+	gs->optindex = 1;
+
+	if (gs->optind >= argc || argv[gs->optind][0] == '-') {
+		if (!silent)
+			printf("option requires an argument -- %c\n", curopt);
+		gs->optopt = curopt;
+		return ':';
+	}
+
+	gs->optarg = argv[gs->optind++];
+	return curopt;
+}
-- 
2.28.0

  parent reply	other threads:[~2020-10-06 19:16 UTC|newest]

Thread overview: 32+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2020-10-06 19:15 [PATCH 00/18] log: Add commands for manipulating filters Sean Anderson
2020-10-06 19:15 ` [PATCH 01/18] log: Fix missing negation of ENOMEM Sean Anderson
2020-10-06 20:36   ` Heinrich Schuchardt
2020-10-06 19:15 ` [PATCH 02/18] log: Fix incorrect documentation of log_filter.cat_list Sean Anderson
2020-10-06 20:41   ` Heinrich Schuchardt
2020-10-06 19:15 ` [PATCH 03/18] log: Add new category names to log_cat_name Sean Anderson
2020-10-06 20:45   ` Heinrich Schuchardt
2020-10-06 19:15 ` [PATCH 04/18] log: Use CONFIG_IS_ENABLED() for LOG_TEST Sean Anderson
2020-10-06 19:15 ` [PATCH 05/18] log: Expose log_device_find_by_name Sean Anderson
2020-10-06 19:15 ` [PATCH 06/18] log: Add function to create a filter with flags Sean Anderson
2020-10-06 19:15 ` [PATCH 07/18] log: Add filter flag to deny on match Sean Anderson
2020-10-06 19:16 ` [PATCH 08/18] test: Add tests for LOGFF_DENY Sean Anderson
2020-10-06 19:16 ` [PATCH 09/18] log: Add filter flag to match greater than a log level Sean Anderson
2020-10-06 19:16 ` [PATCH 10/18] test: Add test for LOGFF_MIN Sean Anderson
2020-10-06 19:16 ` [PATCH 11/18] cmd: log: Use sub-commands for log Sean Anderson
2020-10-06 19:16 ` [PATCH 12/18] cmd: log: Split off log level parsing Sean Anderson
2020-10-06 19:16 ` Sean Anderson [this message]
2020-10-06 19:16 ` [PATCH 14/18] test: Add a test for getopt Sean Anderson
2020-10-06 19:16 ` [PATCH 15/18] cmd: log: Add commands to manipulate filters Sean Anderson
2020-10-06 21:14   ` Heinrich Schuchardt
2020-10-06 21:51     ` Sean Anderson
2020-10-06 22:02   ` Simon Glass
2020-10-06 22:04     ` Sean Anderson
2020-10-06 19:16 ` [PATCH 16/18] test: py: Add a test for log filter-* Sean Anderson
2020-10-06 22:07   ` Simon Glass
2020-10-06 22:09     ` Sean Anderson
2020-10-06 19:16 ` [PATCH 17/18] doc: Add log kerneldocs to documentation Sean Anderson
2020-10-06 19:16 ` [PATCH 18/18] doc: Update logging documentation Sean Anderson
2020-10-06 20:34   ` Heinrich Schuchardt
2020-10-06 20:38     ` Sean Anderson
2020-10-06 21:28       ` Heinrich Schuchardt
2020-10-06 22:00         ` Sean Anderson

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20201006191610.761899-14-seanga2@gmail.com \
    --to=seanga2@gmail.com \
    --cc=u-boot@lists.denx.de \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox