]> git.sur5r.net Git - i3/i3/blob - libi3/mkdirp.c
Allow complete-run.pl to be run from any directory
[i3/i3] / libi3 / mkdirp.c
1 #include "libi3.h"
2 #include <errno.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/stat.h>
6
7 /*
8  * Emulates mkdir -p (creates any missing folders)
9  *
10  */
11 bool mkdirp(const char *path) {
12     if (mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == 0)
13         return true;
14     if (errno != ENOENT) {
15         ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
16         return false;
17     }
18     char *copy = sstrdup(path);
19     /* strip trailing slashes, if any */
20     while (copy[strlen(copy) - 1] == '/')
21         copy[strlen(copy) - 1] = '\0';
22
23     char *sep = strrchr(copy, '/');
24     if (sep == NULL) {
25         if (copy != NULL) {
26             free(copy);
27             copy = NULL;
28         }
29         return false;
30     }
31     *sep = '\0';
32     bool result = false;
33     if (mkdirp(copy))
34         result = mkdirp(path);
35     free(copy);
36
37     return result;
38 }