tools.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <ccan/talloc/talloc.h>
  2. #include <ccan/grab_file/grab_file.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <stdarg.h>
  6. #include <errno.h>
  7. #include "tools.h"
  8. char *talloc_basename(const void *ctx, const char *dir)
  9. {
  10. char *p = strrchr(dir, '/');
  11. if (!p)
  12. return (char *)dir;
  13. return talloc_strdup(ctx, p+1);
  14. }
  15. char *talloc_dirname(const void *ctx, const char *dir)
  16. {
  17. char *p = strrchr(dir, '/');
  18. if (!p)
  19. return talloc_strdup(ctx, ".");
  20. return talloc_strndup(ctx, dir, p - dir);
  21. }
  22. char *talloc_getcwd(const void *ctx)
  23. {
  24. unsigned int len;
  25. char *cwd;
  26. /* *This* is why people hate C. */
  27. len = 32;
  28. cwd = talloc_array(ctx, char, len);
  29. while (!getcwd(cwd, len)) {
  30. if (errno != ERANGE) {
  31. talloc_free(cwd);
  32. return NULL;
  33. }
  34. cwd = talloc_realloc(ctx, cwd, char, len *= 2);
  35. }
  36. return cwd;
  37. }
  38. char *run_command(const void *ctx, const char *fmt, ...)
  39. {
  40. va_list ap;
  41. char *cmd, *contents;
  42. FILE *pipe;
  43. va_start(ap, fmt);
  44. cmd = talloc_vasprintf(ctx, fmt, ap);
  45. va_end(ap);
  46. /* Ensure stderr gets to us too. */
  47. cmd = talloc_asprintf_append(cmd, " 2>&1");
  48. pipe = popen(cmd, "r");
  49. if (!pipe)
  50. return talloc_asprintf(ctx, "Failed to run '%s'", cmd);
  51. contents = grab_fd(cmd, fileno(pipe), NULL);
  52. if (pclose(pipe) != 0)
  53. return talloc_asprintf(ctx, "Running '%s':\n%s",
  54. cmd, contents);
  55. talloc_free(cmd);
  56. return NULL;
  57. }