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