tools: don't assume modules are immediately below ccan/ dir.
[ccan] / tools / ccan_dir.c
1 #include <ccan/talloc/talloc.h>
2 #include <ccan/err/err.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 = talloc_getcwd(NULL);
31                         find_ccan_dir(talloc_asprintf(tmpctx, "%s/%s",
32                                                       tmpctx, base));
33                         talloc_free(tmpctx);
34                 } else {
35                         unsigned int prefix = ccan_dir_prefix(base);
36                         if (prefix)
37                                 ccan_dir = talloc_strndup(NULL, base, prefix);
38                 }
39         }
40         return ccan_dir;
41 }