compat / setenv.con commit Merge branch 'jc/grep-commandline-vs-configuration' into maint (7b163e9)
   1#include "../git-compat-util.h"
   2
   3int gitsetenv(const char *name, const char *value, int replace)
   4{
   5        int out;
   6        size_t namelen, valuelen;
   7        char *envstr;
   8
   9        if (!name || strchr(name, '=') || !value) {
  10                errno = EINVAL;
  11                return -1;
  12        }
  13        if (!replace) {
  14                char *oldval = NULL;
  15                oldval = getenv(name);
  16                if (oldval) return 0;
  17        }
  18
  19        namelen = strlen(name);
  20        valuelen = strlen(value);
  21        envstr = malloc(st_add3(namelen, valuelen, 2));
  22        if (!envstr) {
  23                errno = ENOMEM;
  24                return -1;
  25        }
  26
  27        memcpy(envstr, name, namelen);
  28        envstr[namelen] = '=';
  29        memcpy(envstr + namelen + 1, value, valuelen);
  30        envstr[namelen + valuelen + 1] = 0;
  31
  32        out = putenv(envstr);
  33        /* putenv(3) makes the argument string part of the environment,
  34         * and changing that string modifies the environment --- which
  35         * means we do not own that storage anymore.  Do not free
  36         * envstr.
  37         */
  38
  39        return out;
  40}