75 lines
1.2 KiB
C
75 lines
1.2 KiB
C
#include "command.h"
|
|
|
|
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
|
|
static int command_name_compare(const char *cmd_name, const char *target)
|
|
{
|
|
int score = 0;
|
|
|
|
for (size_t i = 0;; i++) {
|
|
if (cmd_name[i] != target[i]) {
|
|
break;
|
|
}
|
|
|
|
if (!cmd_name[i]) {
|
|
break;
|
|
}
|
|
|
|
score++;
|
|
}
|
|
|
|
return score;
|
|
}
|
|
|
|
const struct command *command_find(
|
|
const struct command **commands,
|
|
size_t nr_commands,
|
|
const char *name)
|
|
{
|
|
int best_score = 0;
|
|
const struct command *best_match = NULL;
|
|
bool ambiguous = false;
|
|
|
|
for (size_t i = 0; i < nr_commands; i++) {
|
|
int score = command_name_compare(commands[i]->cmd_name, name);
|
|
if (score == best_score && score > 0) {
|
|
ambiguous = true;
|
|
}
|
|
|
|
if (score > best_score) {
|
|
ambiguous = false;
|
|
best_score = score;
|
|
best_match = commands[i];
|
|
}
|
|
}
|
|
|
|
if (!best_match) {
|
|
printf("'%s' is not a valid command.\n", name);
|
|
return NULL;
|
|
}
|
|
|
|
if (!ambiguous) {
|
|
return best_match;
|
|
}
|
|
|
|
printf("command name '%s' is ambiguous, and could refer to multiple "
|
|
"commands.\n",
|
|
name);
|
|
return NULL;
|
|
}
|
|
|
|
int command_execute(
|
|
const struct command *cmd,
|
|
struct debug_context *ctx,
|
|
int argc,
|
|
const char **argv,
|
|
void *argp)
|
|
{
|
|
if (!cmd->cmd_callback) {
|
|
return -1;
|
|
}
|
|
|
|
return cmd->cmd_callback(cmd, ctx, argc, argv, argp);
|
|
}
|