X-Git-Url: https://git.ozlabs.org/?p=ccan;a=blobdiff_plain;f=tools%2Ftools.c;h=b93448278648034f8835668db5476cc6abe038c5;hp=b7beda72b9c5b6cf0a5ec8beffb34d535887b6a3;hb=afcb4f4dd0d88c699d816883d62c8cff5f37ca0d;hpb=501e192029768948a81aeef6515f5d0dd6519f37 diff --git a/tools/tools.c b/tools/tools.c index b7beda72..b9344827 100644 --- a/tools/tools.c +++ b/tools/tools.c @@ -14,10 +14,10 @@ #include #include #include +#include #include "tools.h" static char *tmpdir = NULL; -static unsigned int count; bool tools_verbose = false; /* Ten minutes. */ @@ -28,7 +28,7 @@ char *talloc_basename(const void *ctx, const char *dir) char *p = strrchr(dir, '/'); if (!p) - return (char *)dir; + return talloc_strdup(ctx, dir); return talloc_strdup(ctx, p+1); } @@ -204,34 +204,43 @@ char *temp_dir(const void *ctx) err(1, "mkdir %s failed", tmpdir); } talloc_set_destructor(tmpdir, unlink_all); + if (tools_verbose) + printf("Created temporary directory %s\n", tmpdir); } - if (tools_verbose) - printf("Created temporary directory %s\n", tmpdir); return tmpdir; } -char *temp_file(const void *ctx, const char *extension) -{ - char *f = talloc_asprintf(ctx, "%s/%u%s", - temp_dir(ctx), count++, extension); - if (tools_verbose) - printf("Created temporary file %s\n", f); - return f; -} - char *maybe_temp_file(const void *ctx, const char *extension, bool keep, const char *srcname) { - size_t baselen; - char *f; + unsigned baselen; + char *f, *suffix = talloc_strdup(ctx, ""); + struct stat st; + unsigned int count = 0; if (!keep) - return temp_file(ctx, extension); + srcname = talloc_basename(ctx, srcname); + else + assert(srcname[0] == '/'); + + if (strrchr(srcname, '.')) + baselen = strrchr(srcname, '.') - srcname; + else + baselen = strlen(srcname); + + do { + f = talloc_asprintf(ctx, "%s/%.*s%s%s", + keep ? "" : temp_dir(ctx), + baselen, srcname, + suffix, extension); + talloc_free(suffix); + suffix = talloc_asprintf(ctx, "-%u", ++count); + } while (lstat(f, &st) == 0); - baselen = strrchr(srcname, '.') - srcname; - f = talloc_asprintf(ctx, "%.*s%s", baselen, srcname, extension); if (tools_verbose) printf("Creating file %s\n", f); + + talloc_free(suffix); return f; }