aboutsummaryrefslogtreecommitdiff
path: root/cli/cli-example.c
blob: 8149be05e97f4ebcd1374ca54ee5ec1ae4a7579d (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
 * silly simple example program
 */
#include "cli.h"

long		  distance;
unsigned long time;
long		  speed;

bool murica;

int calc_speed(const struct cli_ctx *ctx)
{
	if (time == 0) {
		fprintf(stderr, "time cannot be zero\n");
		return CLI_RC_BAD_ARGS;
	}
	double speed = (double)distance / ((double)time / 3600);
	printf("%lf%s\n", speed, murica ? "mph" : "km/h");

	return CLI_RC_OK;
}

int calc_distance(const struct cli_ctx *ctx)
{
	double distance = speed * ((double)time / 3600);
	printf("%lf%s\n", distance, murica ? "miles" : "km");

	return CLI_RC_OK;
}

const struct cli_opt speed_opts[] = {
	{
		.type	 = CLI_OT_INT,
		.shor	 = 'd',
		.lon	 = "distance",
		.desc	 = "the distance (km/miles)",
		.value.i = &distance,
	},
	{
		.type	 = CLI_OT_UINT,
		.shor	 = 't',
		.lon	 = "time",
		.desc	 = "the time (seconds)",
		.value.u = &time,
	},
	{0},
};

const struct cli_opt distance_opts[] = {
	{
		.type	 = CLI_OT_INT,
		.shor	 = 's',
		.lon	 = "speed",
		.desc	 = "the speed ((km/miles)ph)",
		.value.i = &speed,
	},
	{
		.type	 = CLI_OT_UINT,
		.shor	 = 't',
		.lon	 = "time",
		.desc	 = "the time (seconds)",
		.value.u = &time,
	},
	{0},
};

const struct cli_cmd my_cmds[] = {
	{
		.name = "speed",
		.desc = "calculate speed",
		.help =
			"Tell me the distance and the time, and I'll tell you your speed",
		.opts = speed_opts,
		.func = calc_speed,
	},
	{
		.name = "distance",
		.desc = "calculate distance",
		.help =
			"Tell me the speed and the time, and I'll tell you your distance",
		.opts = distance_opts,
		.func = calc_distance,
	},
	{0},
};

struct cli_opt global_opts[] = {
	{
		.type	 = CLI_OT_FLAG,
		.shor	 = 'M',
		.lon	 = "murica",
		.desc	 = "Use American™ measurements",
		.value.f = &murica,
	},
	{0},
};

struct cli my_cli = {
	.header = "This is an example CLI program",
	.footer = "\nCopyright (c) 2025 Yaroslav de la Peña Smirnov "
			  "<yps@yaroslavps.com>",
	.cmds	= my_cmds,
	.opts	= global_opts,
};

int main(int argc, char *argv[])
{
	return cli_run(&my_cli, argc, argv);
}