Add compat/setenv.c, use in git.c.
[alt-git.git] / compat / setenv.c
blob94acd2da9e2e95f9f9a72061d9575de6079dcaec
1 #include <stdlib.h>
2 #include <string.h>
4 int gitsetenv(const char *name, const char *value, int replace)
6 int out;
7 size_t namelen, valuelen;
8 char *envstr;
10 if (!name || !value) return -1;
11 if (!replace) {
12 char *oldval = NULL;
13 oldval = getenv(name);
14 if (oldval) return 0;
17 namelen = strlen(name);
18 valuelen = strlen(value);
19 envstr = malloc((namelen + valuelen + 2) * sizeof(char));
20 if (!envstr) return -1;
22 memcpy(envstr, name, namelen);
23 envstr[namelen] = '=';
24 memcpy(envstr + namelen + 1, value, valuelen);
25 envstr[namelen + valuelen + 1] = 0;
27 out = putenv(envstr);
29 free(envstr);
30 return out;