~lattis/muon

ref: 49a50d56c57dfdf470b4bcbffc16bc5ec92dcb4e muon/src/opts.c -rw-r--r-- 1.6 KiB
49a50d56Stone Tickle support comma seperated option array 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "posix.h"

#include <getopt.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "lang/workspace.h"
#include "log.h"
#include "opts.h"

bool
check_operands(uint32_t argc, uint32_t argi, int32_t expected)
{
	assert(argc >= argi);

	uint32_t rem = argc - argi;

	if (expected < 0) {
		return true;
	}

	if (rem < (uint32_t)expected) {
		LOG_E("missing operand");
		return false;
	} else if (rem > (uint32_t)expected) {
		LOG_E("too many operands (did you try passing options after operands?)");
		return false;
	}

	return true;
}

void
print_usage(FILE *f, const struct command *commands,
	const char *pre, const char *opts, const char *post)
{
	uint32_t i;
	fprintf(f, "usage: %s%s%s%s\n",
		pre,
		opts ?  " [opts]" : "",
		commands ?  " [command]" : "",
		post ? post : ""
		);

	if (opts) {
		fprintf(f,
			"opts:\n"
			"%s"
			"  -h - show this message\n",
			opts);
	}

	if (commands) {
		fprintf(f, "commands:\n");

		for (i = 0; commands[i].name; ++i) {
			fprintf(f, "  %-10s", commands[i].name);

			if (commands[i].desc) {
				fprintf(f, "- %s", commands[i].desc);
			}

			fputc('\n', f);
		}
	}
}

bool
find_cmd(const struct command *commands, cmd_func *ret,
	uint32_t argc, uint32_t argi, char *const argv[], bool optional)
{
	uint32_t i;
	const char *cmd;

	if (argi >= argc) {
		if (optional) {
			*ret = NULL;
			return true;
		} else {
			LOG_E("missing command");
			return false;
		}
	} else {
		cmd = argv[argi];
	}

	for (i = 0; commands[i].name; ++i) {
		if (strcmp(commands[i].name, cmd) == 0) {
			*ret = commands[i].cmd;
			return true;
		}
	}

	LOG_E("invalid command '%s'", cmd);
	return false;
}