]> git.sur5r.net Git - i3/i3/blob - libi3/resolve_tilde.c
resolve_tilde: strncpy + strlen is pointless (#3436)
[i3/i3] / libi3 / resolve_tilde.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include "libi3.h"
9
10 #include <err.h>
11 #include <glob.h>
12 #include <stdlib.h>
13 #include <string.h>
14
15 /*
16  * This function resolves ~ in pathnames.
17  * It may resolve wildcards in the first part of the path, but if no match
18  * or multiple matches are found, it just returns a copy of path as given.
19  *
20  */
21 char *resolve_tilde(const char *path) {
22     static glob_t globbuf;
23     char *head, *tail, *result;
24
25     tail = strchr(path, '/');
26     head = sstrndup(path, tail ? (size_t)(tail - path) : strlen(path));
27
28     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
29     free(head);
30     /* no match, or many wildcard matches are bad */
31     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
32         result = sstrdup(path);
33     else if (res != 0) {
34         err(EXIT_FAILURE, "glob() failed");
35     } else {
36         head = globbuf.gl_pathv[0];
37         result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1, 1);
38         strcpy(result, head);
39         if (tail) {
40             strcat(result, tail);
41         }
42     }
43     globfree(&globbuf);
44
45     return result;
46 }