Sync with 'maint'
[git/gitster.git] / compat / setenv.c
blob7849f258d20195ac27c9be921fb8b65ac094a408
1 #include "../git-compat-util.h"
3 int gitsetenv(const char *name, const char *value, int replace)
5 int out;
6 size_t namelen, valuelen;
7 char *envstr;
9 if (!name || strchr(name, '=') || !value) {
10 errno = EINVAL;
11 return -1;
13 if (!replace) {
14 char *oldval = NULL;
15 oldval = getenv(name);
16 if (oldval) return 0;
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;
27 memcpy(envstr, name, namelen);
28 envstr[namelen] = '=';
29 memcpy(envstr + namelen + 1, value, valuelen);
30 envstr[namelen + valuelen + 1] = 0;
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.
39 return out;