diff mbox series

[3/4] mmc-utils: Introduce a generic print_usage function

Message ID 20250428122951.317055-4-avri.altman@sandisk.com
State New
Headers show
Series mmc-utils: Reuse the 'help' section for command usage handling | expand

Commit Message

Avri Altman April 28, 2025, 12:29 p.m. UTC
This patch introduces a generic `print_usage` function to centralize the
handling of command usage messages. It reuses and prints the usage
information stored in the `help` field of the `struct Command`.

This refactoring simplifies command-specific usage handling by
centralizing it in a reusable function, reducing redundancy and
improving maintainability.

Signed-off-by: Avri Altman <avri.altman@sandisk.com>
---
 mmc.c      | 18 +++++++++++++++++-
 mmc_cmds.h |  4 ++++
 2 files changed, 21 insertions(+), 1 deletion(-)
diff mbox series

Patch

diff --git a/mmc.c b/mmc.c
index 6e834ca..315fa70 100644
--- a/mmc.c
+++ b/mmc.c
@@ -26,7 +26,7 @@ 
 
 #include "mmc_cmds.h"
 
-typedef int (*CommandFunction)(int argc, char **argv);
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
 
 struct Command {
 	CommandFunction	func;	/* function which implements the command */
@@ -545,6 +545,22 @@  static int parse_args(int argc, char **argv,
 
 	return 1;
 }
+
+void print_usage(CommandFunction func)
+{
+	int num_commands = ARRAY_SIZE(commands);
+	int i;
+
+	for (i = 0; i < num_commands; i++) {
+		if (commands[i].func == func) {
+			print_help(&commands[i]);
+			return;
+		}
+	}
+
+	fprintf(stderr, "Error: Command not found for the given function pointer.\n");
+}
+
 int main(int ac, char **av )
 {
 	char *cmd = NULL, **args = NULL;
diff --git a/mmc_cmds.h b/mmc_cmds.h
index d83fb57..ce35d3e 100644
--- a/mmc_cmds.h
+++ b/mmc_cmds.h
@@ -17,6 +17,10 @@ 
  * those modifications are Copyright (c) 2016 SanDisk Corp.
  */
 
+typedef int (*CommandFunction)(int argc, char **argv);
+
+void print_usage(CommandFunction func);
+
 /* mmc_cmds.c */
 int do_read_extcsd(int nargs, char **argv);
 int do_write_extcsd(int nargs, char **argv);