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