ntdb: assume HAVE_CCAN in header.
[ccan] / tools / ccan_dir.c
1 #include <ccan/err/err.h>
2 #include <ccan/tal/path/path.h>
3 #include "tools.h"
4 #include <assert.h>
5 #include <string.h>
6 #include <stdlib.h>
7
8 /* Walk up to find /ccan/ => ccan directory. */
9 static unsigned int ccan_dir_prefix(const char *fulldir)
10 {
11         unsigned int i;
12
13         assert(fulldir[0] == '/');
14         for (i = strlen(fulldir) - 1; i > 0; i--) {
15                 if (strncmp(fulldir+i, "/ccan", 5) != 0)
16                         continue;
17                 if (fulldir[i+5] != '\0' && fulldir[i+5] != '/')
18                         continue;
19                 return i + 1;
20         }
21         return 0;
22 }
23
24 const char *find_ccan_dir(const char *base)
25 {
26         static char *ccan_dir;
27
28         if (!ccan_dir) {
29                 if (base[0] != '/') {
30                         const char *tmpctx = path_cwd(NULL);
31                         find_ccan_dir(path_join(tmpctx, tmpctx, base));
32                         tal_free(tmpctx);
33                 } else {
34                         unsigned int prefix = ccan_dir_prefix(base);
35                         if (prefix)
36                                 ccan_dir = tal_strndup(NULL, base, prefix);
37                 }
38         }
39         return ccan_dir;
40 }