xref: /kvmtool/kvm-cmd.c (revision f6677a1decac9ff0b48fa59f1a684387352e72bd)
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 
5 #include <assert.h>
6 
7 /* user defined header files */
8 #include <kvm/kvm-cmd.h>
9 #include <kvm/kvm-help.h>
10 #include <kvm/kvm-run.h>
11 
12 struct cmd_struct kvm_commands[] = {
13 	{ "help",  kvm_cmd_help,  NULL,         0 },
14 	{ "run",   kvm_cmd_run,   kvm_run_help, 0 },
15 	{ NULL,    NULL,          NULL,         0 },
16 };
17 
18 /*
19  * kvm_get_command: Searches the command in an array of the commands and
20  * returns a pointer to cmd_struct if a match is found.
21  *
22  * Input parameters:
23  * command: Array of possible commands. The last entry in the array must be
24  *          NULL.
25  * cmd: A string command to search in the array
26  *
27  * Return Value:
28  * NULL: If the cmd is not matched with any of the command in the command array
29  * p: Pointer to cmd_struct of the matching command
30  */
31 struct cmd_struct *kvm_get_command(struct cmd_struct *command,
32 		const char *cmd)
33 {
34 	struct cmd_struct *p = command;
35 
36 	while (p->cmd) {
37 		if (!strcmp(p->cmd, cmd))
38 			return p;
39 		p++;
40 	}
41 	return NULL;
42 }
43 
44 int handle_command(struct cmd_struct *command, int argc, const char **argv)
45 {
46 	struct cmd_struct *p;
47 	const char *prefix = NULL;
48 
49 	if (!argv || !*argv) {
50 		p = kvm_get_command(command, "help");
51 		assert(p);
52 		return p->fn(argc, argv, prefix);
53 	}
54 
55 	p = kvm_get_command(command, argv[0]);
56 	if (!p) {
57 		p = kvm_get_command(command, "help");
58 		assert(p);
59 		p->fn(0, NULL, prefix);
60 		return EINVAL;
61 	}
62 
63 	return p->fn(argc - 1, &argv[1], prefix);
64 }
65