run-command: add env_array, an optional argv_array for env

Similar to args, add a struct argv_array member to struct child_process that simplifies specifying the environment for children. It is freed automatically by finish_command() or if start_command() encounters an error. Suggested-by: Jeff King <peff@peff.net> Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Oct 19, 2014 at 13:13 UTC 19a583dc39e3e1110f746e837c5ce1953d6ebfa1
3 files changed +13 -1
Documentation/technical/api-run-command.txt
+5
@@ -169,6 +169,11 @@ string pointers (NULL terminated) in .env:
169 . If the string does not contain '=', it names an environment
170 variable that will be removed from the child process's environment.
171
172 +If the .env member is NULL, `start_command` will point it at the
173 +.env_array `argv_array` (so you may use one or the other, but not both).
174 +The memory in .env_array will be cleaned up automatically during
175 +`finish_command` (or during `start_command` when it is unsuccessful).
176 +
177 To specify a new initial working directory for the sub-process,
178 specify it in the .dir member.
179
run-command.c
+6
@@ -12,6 +12,7 @@ void child_process_init(struct child_process *child)
12 {
13 memset(child, 0, sizeof(*child));
14 argv_array_init(&child->args);
15 + argv_array_init(&child->env_array);
16 }
17
18 struct child_to_clean {
@@ -287,6 +288,8 @@ int start_command(struct child_process *cmd)
288
289 if (!cmd->argv)
290 cmd->argv = cmd->args.argv;
291 + if (!cmd->env)
292 + cmd->env = cmd->env_array.argv;
293
294 /*
295 * In case of errors we must keep the promise to close FDs
@@ -338,6 +341,7 @@ fail_pipe:
341 error("cannot create %s pipe for %s: %s",
342 str, cmd->argv[0], strerror(failed_errno));
343 argv_array_clear(&cmd->args);
344 + argv_array_clear(&cmd->env_array);
345 errno = failed_errno;
346 return -1;
347 }
@@ -524,6 +528,7 @@ fail_pipe:
528 else if (cmd->err)
529 close(cmd->err);
530 argv_array_clear(&cmd->args);
531 + argv_array_clear(&cmd->env_array);
532 errno = failed_errno;
533 return -1;
534 }
@@ -550,6 +555,7 @@ int finish_command(struct child_process *cmd)
555 {
556 int ret = wait_or_whine(cmd->pid, cmd->argv[0]);
557 argv_array_clear(&cmd->args);
558 + argv_array_clear(&cmd->env_array);
559 return ret;
560 }
561
run-command.h
+2 -1
@@ -10,6 +10,7 @@
10 struct child_process {
11 const char **argv;
12 struct argv_array args;
13 + struct argv_array env_array;
14 pid_t pid;
15 /*
16 * Using .in, .out, .err:
@@ -44,7 +45,7 @@ struct child_process {
45 unsigned clean_on_exit:1;
46 };
47
47 -#define CHILD_PROCESS_INIT { NULL, ARGV_ARRAY_INIT }
48 +#define CHILD_PROCESS_INIT { NULL, ARGV_ARRAY_INIT, ARGV_ARRAY_INIT }
49 void child_process_init(struct child_process *);
50
51 int start_command(struct child_process *);