Merge branch 'jk/perf-no-dups'
[git/git.git] / compat / setenv.c
CommitLineData
85023577 1#include "../git-compat-util.h"
e40b61fb
JR
2
3int gitsetenv(const char *name, const char *value, int replace)
4{
5 int out;
6 size_t namelen, valuelen;
7 char *envstr;
8
6ac1b2a3 9 if (!name || strchr(name, '=') || !value) {
57590c72
EFL
10 errno = EINVAL;
11 return -1;
12 }
e40b61fb
JR
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);
50a6c8ef 21 envstr = malloc(st_add3(namelen, valuelen, 2));
57590c72
EFL
22 if (!envstr) {
23 errno = ENOMEM;
24 return -1;
25 }
e40b61fb
JR
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);
3a267433
JH
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 */
e40b61fb 38
e40b61fb
JR
39 return out;
40}