cmd_bar: simplify logic

This commit is contained in:
Brian Ashworth 2018-10-12 21:53:40 -04:00
parent 84b28dc593
commit 2a0c7ebd43

View file

@ -46,37 +46,34 @@ static bool is_subcommand(char *name) {
struct cmd_results *cmd_bar(int argc, char **argv) { struct cmd_results *cmd_bar(int argc, char **argv) {
struct cmd_results *error = NULL; struct cmd_results *error = NULL;
if ((error = checkarg(argc, "bar", EXPECTED_AT_LEAST, 1))) { if ((error = checkarg(argc, "bar", EXPECTED_AT_LEAST, 2))) {
return error; return error;
} }
bool spawn = false; bool spawn = false;
if (argc > 1) { struct bar_config *bar = NULL;
struct bar_config *bar = NULL; if (strcmp(argv[0], "id") != 0 && is_subcommand(argv[1])) {
if (!is_subcommand(argv[0]) || for (int i = 0; i < config->bars->length; ++i) {
(strcmp(argv[0], "id") != 0 && is_subcommand(argv[1]))) { struct bar_config *item = config->bars->items[i];
for (int i = 0; i < config->bars->length; ++i) { if (strcmp(item->id, argv[0]) == 0) {
struct bar_config *item = config->bars->items[i]; wlr_log(WLR_DEBUG, "Selecting bar: %s", argv[0]);
if (strcmp(item->id, argv[0]) == 0) { bar = item;
wlr_log(WLR_DEBUG, "Selecting bar: %s", argv[0]); break;
bar = item;
break;
}
} }
if (!bar) {
spawn = !config->reading;
wlr_log(WLR_DEBUG, "Creating bar: %s", argv[0]);
bar = default_bar_config();
if (!bar) {
return cmd_results_new(CMD_FAILURE, "bar",
"Unable to allocate bar state");
}
bar->id = strdup(argv[0]);
}
config->current_bar = bar;
++argv; --argc;
} }
if (!bar) {
spawn = !config->reading;
wlr_log(WLR_DEBUG, "Creating bar: %s", argv[0]);
bar = default_bar_config();
if (!bar) {
return cmd_results_new(CMD_FAILURE, "bar",
"Unable to allocate bar state");
}
bar->id = strdup(argv[0]);
}
config->current_bar = bar;
++argv; --argc;
} }
if (!config->current_bar && config->reading) { if (!config->current_bar && config->reading) {
@ -88,18 +85,13 @@ struct cmd_results *cmd_bar(int argc, char **argv) {
} }
// set bar id // set bar id
for (int i = 0; i < config->bars->length; ++i) { const int len = 5 + numlen(config->bars->length - 1); // "bar-"+i+\0
if (bar == config->bars->items[i]) { bar->id = malloc(len * sizeof(char));
const int len = 5 + numlen(i); // "bar-" + i + \0 if (bar->id) {
bar->id = malloc(len * sizeof(char)); snprintf(bar->id, len, "bar-%d", config->bars->length - 1);
if (bar->id) { } else {
snprintf(bar->id, len, "bar-%d", i); return cmd_results_new(CMD_FAILURE,
} else { "bar", "Unable to allocate bar ID");
return cmd_results_new(CMD_FAILURE,
"bar", "Unable to allocate bar ID");
}
break;
}
} }
// Set current bar // Set current bar