+static COMMAND_HELPER(command_help_find, struct command *head,
+ struct command **out)
+{
+ if (0 == CMD_ARGC)
+ return ERROR_INVALID_ARGUMENTS;
+ *out = command_find(head, CMD_ARGV[0]);
+ if (NULL == *out)
+ return ERROR_INVALID_ARGUMENTS;
+ if (--CMD_ARGC == 0)
+ return ERROR_OK;
+ CMD_ARGV++;
+ return CALL_COMMAND_HANDLER(command_help_find, (*out)->children, out);
+}
+
+static COMMAND_HELPER(command_help_show, struct command *c, unsigned n);
+
+static COMMAND_HELPER(command_help_show_list, struct command *head, unsigned n)
+{
+ for (struct command *c = head; NULL != c; c = c->next)
+ CALL_COMMAND_HANDLER(command_help_show, c, n);
+ return ERROR_OK;
+}
+static COMMAND_HELPER(command_help_show, struct command *c, unsigned n)
+{
+ command_run_linef(CMD_CTX, "cmd_help {%s} {%s} %d", command_name(c, ' '),
+ c->help ? : "no help available", n);
+
+ if (++n >= 2)
+ return ERROR_OK;
+
+ return CALL_COMMAND_HANDLER(command_help_show_list, c->children, n);
+}
+COMMAND_HANDLER(handle_help_command)
+{
+ struct command *c = CMD_CTX->commands;
+
+ if (0 == CMD_ARGC)
+ return CALL_COMMAND_HANDLER(command_help_show_list, c, 0);
+
+ int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c);
+ if (ERROR_OK != retval)
+ return retval;
+
+ return CALL_COMMAND_HANDLER(command_help_show, c, 0);
+}
+
+
+int help_add_command(struct command_context *cmd_ctx, struct command *parent,
+ const char *cmd_name, const char *help_text)
+{
+ struct command **head = command_list_for_parent(cmd_ctx, parent);
+ struct command *nc = command_find(*head, cmd_name);
+ if (NULL == nc)
+ {
+ // add a new command with help text
+ nc = register_command(cmd_ctx, parent, cmd_name,
+ NULL, COMMAND_ANY, help_text);
+ if (NULL == nc)
+ {
+ LOG_ERROR("failed to add '%s' help text", cmd_name);
+ return ERROR_FAIL;
+ }
+ LOG_DEBUG("added '%s' help text", cmd_name);
+ }
+ else
+ {
+ bool replaced = false;
+ if (nc->help)
+ {
+ free((void *)nc->help);
+ replaced = true;
+ }
+ nc->help = strdup(help_text);
+
+ if (replaced)
+ LOG_INFO("replaced existing '%s' help", cmd_name);
+ else
+ LOG_DEBUG("added '%s' help text", cmd_name);
+ }
+ return ERROR_OK;
+}
+
+COMMAND_HANDLER(handle_help_add_command)
+{
+ if (CMD_ARGC < 2)
+ {
+ LOG_ERROR("%s: insufficient arguments", CMD_NAME);
+ return ERROR_INVALID_ARGUMENTS;
+ }
+
+ // save help text and remove it from argument list
+ const char *help_text = CMD_ARGV[--CMD_ARGC];
+ // likewise for the leaf command name
+ const char *cmd_name = CMD_ARGV[--CMD_ARGC];
+
+ struct command *c = NULL;
+ if (CMD_ARGC > 0)
+ {
+ c = CMD_CTX->commands;
+ int retval = CALL_COMMAND_HANDLER(command_help_find, c, &c);
+ if (ERROR_OK != retval)
+ return retval;
+ }
+ return help_add_command(CMD_CTX, c, cmd_name, help_text);
+}
+
+/* sleep command sleeps for <n> miliseconds
+ * this is useful in target startup scripts
+ */
+COMMAND_HANDLER(handle_sleep_command)