ccan_dir.c 863 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. /* Walk up to find /ccan/ => ccan directory. */
  8. static unsigned int ccan_dir_prefix(const char *fulldir)
  9. {
  10. unsigned int i;
  11. assert(fulldir[0] == '/');
  12. for (i = strlen(fulldir) - 1; i > 0; i--) {
  13. if (strncmp(fulldir+i, "/ccan", 5) != 0)
  14. continue;
  15. if (fulldir[i+5] != '\0' && fulldir[i+5] != '/')
  16. continue;
  17. return i + 1;
  18. }
  19. return 0;
  20. }
  21. const char *find_ccan_dir(const char *base)
  22. {
  23. static char *ccan_dir;
  24. if (!ccan_dir) {
  25. if (base[0] != '/') {
  26. const char *tmpctx = path_cwd(NULL);
  27. find_ccan_dir(path_join(tmpctx, tmpctx, base));
  28. tal_free(tmpctx);
  29. } else {
  30. unsigned int prefix = ccan_dir_prefix(base);
  31. if (prefix)
  32. ccan_dir = tal_strndup(NULL, base, prefix);
  33. }
  34. }
  35. return ccan_dir;
  36. }