path.con commit [PATCH] Add -k kill keyword expansion option to git-cvsimport - revised (abe0582)
   1/*
   2 * I'm tired of doing "vsnprintf()" etc just to open a
   3 * file, so here's a "return static buffer with printf"
   4 * interface for paths.
   5 *
   6 * It's obviously not thread-safe. Sue me. But it's quite
   7 * useful for doing things like
   8 *
   9 *   f = open(mkpath("%s/%s.git", base, name), O_RDONLY);
  10 *
  11 * which is what it's designed for.
  12 */
  13#include "cache.h"
  14
  15static char pathname[PATH_MAX];
  16static char bad_path[] = "/bad-path/";
  17
  18static char *cleanup_path(char *path)
  19{
  20        /* Clean it up */
  21        if (!memcmp(path, "./", 2)) {
  22                path += 2;
  23                while (*path == '/')
  24                        path++;
  25        }
  26        return path;
  27}
  28
  29char *mkpath(const char *fmt, ...)
  30{
  31        va_list args;
  32        unsigned len;
  33
  34        va_start(args, fmt);
  35        len = vsnprintf(pathname, PATH_MAX, fmt, args);
  36        va_end(args);
  37        if (len >= PATH_MAX)
  38                return bad_path;
  39        return cleanup_path(pathname);
  40}
  41
  42char *git_path(const char *fmt, ...)
  43{
  44        const char *git_dir = gitenv(GIT_DIR_ENVIRONMENT) ? : DEFAULT_GIT_DIR_ENVIRONMENT;
  45        va_list args;
  46        unsigned len;
  47
  48        len = strlen(git_dir);
  49        if (len > PATH_MAX-100)
  50                return bad_path;
  51        memcpy(pathname, git_dir, len);
  52        if (len && git_dir[len-1] != '/')
  53                pathname[len++] = '/';
  54        va_start(args, fmt);
  55        len += vsnprintf(pathname + len, PATH_MAX - len, fmt, args);
  56        va_end(args);
  57        if (len >= PATH_MAX)
  58                return bad_path;
  59        return cleanup_path(pathname);
  60}
  61
  62
  63/* git_mkstemp() - create tmp file honoring TMPDIR variable */
  64int git_mkstemp(char *path, size_t len, const char *template)
  65{
  66        char *env, *pch = path;
  67
  68        if ((env = getenv("TMPDIR")) == NULL) {
  69                strcpy(pch, "/tmp/");
  70                len -= 5;
  71                pch += 5;
  72        } else {
  73                size_t n = snprintf(pch, len, "%s/", env);
  74
  75                len -= n;
  76                pch += n;
  77        }
  78
  79        safe_strncpy(pch, template, len);
  80
  81        return mkstemp(path);
  82}
  83
  84
  85char *safe_strncpy(char *dest, const char *src, size_t n)
  86{
  87        strncpy(dest, src, n);
  88        dest[n - 1] = '\0';
  89
  90        return dest;
  91}