diff options
author | Zandr Martin <zandrmartin@gmail.com> | 2016-09-01 21:39:08 -0500 |
---|---|---|
committer | Zandr Martin <zandrmartin@gmail.com> | 2016-09-01 21:39:08 -0500 |
commit | b374c35758777f98e5ddbe4b0dc43bd7c80f36d7 (patch) | |
tree | 04bb4cfc3da7d2e0de7fbc38db42f65c66d2df4c /sway/commands/set.c | |
parent | Merge pull request #874 from yohanesu75/ipc-client-fix (diff) | |
download | sway-b374c35758777f98e5ddbe4b0dc43bd7c80f36d7.tar.gz sway-b374c35758777f98e5ddbe4b0dc43bd7c80f36d7.tar.zst sway-b374c35758777f98e5ddbe4b0dc43bd7c80f36d7.zip |
refactor commands.c
Diffstat (limited to 'sway/commands/set.c')
-rw-r--r-- | sway/commands/set.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/sway/commands/set.c b/sway/commands/set.c new file mode 100644 index 00000000..b82a30ac --- /dev/null +++ b/sway/commands/set.c | |||
@@ -0,0 +1,56 @@ | |||
1 | #include <stdio.h> | ||
2 | #include <string.h> | ||
3 | #include "commands.h" | ||
4 | #include "config.h" | ||
5 | #include "list.h" | ||
6 | #include "stringop.h" | ||
7 | |||
8 | // sort in order of longest->shortest | ||
9 | static int compare_set_qsort(const void *_l, const void *_r) { | ||
10 | struct sway_variable const *l = *(void **)_l; | ||
11 | struct sway_variable const *r = *(void **)_r; | ||
12 | return strlen(r->name) - strlen(l->name); | ||
13 | } | ||
14 | |||
15 | struct cmd_results *cmd_set(int argc, char **argv) { | ||
16 | char *tmp; | ||
17 | int size; | ||
18 | struct cmd_results *error = NULL; | ||
19 | if (!config->reading) return cmd_results_new(CMD_FAILURE, "set", "Can only be used in config file."); | ||
20 | if ((error = checkarg(argc, "set", EXPECTED_AT_LEAST, 2))) { | ||
21 | return error; | ||
22 | } | ||
23 | |||
24 | if (argv[0][0] != '$') { | ||
25 | sway_log(L_INFO, "Warning: variable '%s' doesn't start with $", argv[0]); | ||
26 | |||
27 | size = asprintf(&tmp, "%s%s", "$", argv[0]); | ||
28 | if (size == -1) { | ||
29 | return cmd_results_new(CMD_FAILURE, "set", "Not possible to create variable $'%s'", argv[0]); | ||
30 | } | ||
31 | |||
32 | argv[0] = strdup(tmp); | ||
33 | free(tmp); | ||
34 | } | ||
35 | |||
36 | struct sway_variable *var = NULL; | ||
37 | // Find old variable if it exists | ||
38 | int i; | ||
39 | for (i = 0; i < config->symbols->length; ++i) { | ||
40 | var = config->symbols->items[i]; | ||
41 | if (strcmp(var->name, argv[0]) == 0) { | ||
42 | break; | ||
43 | } | ||
44 | var = NULL; | ||
45 | } | ||
46 | if (var) { | ||
47 | free(var->value); | ||
48 | } else { | ||
49 | var = malloc(sizeof(struct sway_variable)); | ||
50 | var->name = strdup(argv[0]); | ||
51 | list_add(config->symbols, var); | ||
52 | list_qsort(config->symbols, compare_set_qsort); | ||
53 | } | ||
54 | var->value = join_args(argv + 1, argc - 1); | ||
55 | return cmd_results_new(CMD_SUCCESS, NULL, NULL); | ||
56 | } | ||