setenv.c 862 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include "../git-compat-util.h"
  2. int gitsetenv(const char *name, const char *value, int replace)
  3. {
  4. int out;
  5. size_t namelen, valuelen;
  6. char *envstr;
  7. if (!name || strchr(name, '=') || !value) {
  8. errno = EINVAL;
  9. return -1;
  10. }
  11. if (!replace) {
  12. char *oldval = NULL;
  13. oldval = getenv(name);
  14. if (oldval) return 0;
  15. }
  16. namelen = strlen(name);
  17. valuelen = strlen(value);
  18. envstr = malloc(st_add3(namelen, valuelen, 2));
  19. if (!envstr) {
  20. errno = ENOMEM;
  21. return -1;
  22. }
  23. memcpy(envstr, name, namelen);
  24. envstr[namelen] = '=';
  25. memcpy(envstr + namelen + 1, value, valuelen);
  26. envstr[namelen + valuelen + 1] = 0;
  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. return out;
  34. }