1 #include <ccan/talloc/talloc.h>
2 #include <ccan/grab_file/grab_file.h>
12 static char *tmpdir = NULL;
13 static unsigned int count;
15 char *talloc_basename(const void *ctx, const char *dir)
17 char *p = strrchr(dir, '/');
21 return talloc_strdup(ctx, p+1);
24 char *talloc_dirname(const void *ctx, const char *dir)
26 char *p = strrchr(dir, '/');
29 return talloc_strdup(ctx, ".");
30 return talloc_strndup(ctx, dir, p - dir);
33 char *talloc_getcwd(const void *ctx)
38 /* *This* is why people hate C. */
40 cwd = talloc_array(ctx, char, len);
41 while (!getcwd(cwd, len)) {
42 if (errno != ERANGE) {
46 cwd = talloc_realloc(ctx, cwd, char, len *= 2);
51 /* Returns output if command fails. */
52 char *run_command(const void *ctx, const char *fmt, ...)
59 cmd = talloc_vasprintf(ctx, fmt, ap);
62 /* Ensure stderr gets to us too. */
63 cmd = talloc_asprintf_append(cmd, " 2>&1");
65 pipe = popen(cmd, "r");
67 return talloc_asprintf(ctx, "Failed to run '%s'", cmd);
69 contents = grab_fd(cmd, fileno(pipe), NULL);
70 if (pclose(pipe) != 0)
71 return talloc_asprintf(ctx, "Running '%s':\n%s",
78 static int unlink_all(char *dir)
80 char cmd[strlen(dir) + sizeof("rm -rf ")];
81 sprintf(cmd, "rm -rf %s", dir);
83 warn("Could not remove temporary work in %s", dir);
87 char *temp_file(const void *ctx, const char *extension)
89 /* For first call, create dir. */
91 tmpdir = getenv("TMPDIR");
94 tmpdir = talloc_asprintf(talloc_autofree_context(),
96 tmpdir, getpid(), random());
97 if (mkdir(tmpdir, 0700) != 0) {
98 if (errno == EEXIST) {
103 err(1, "mkdir %s failed", tmpdir);
105 talloc_set_destructor(tmpdir, unlink_all);
108 return talloc_asprintf(ctx, "%s/%u%s", tmpdir, count++, extension);