test-tool: handle the `-C <directory>` option just like `git`

In preparation for moving `git serve` into `test-tool` (because it really is only used by the test suite), we teach the `test-tool` the useful trick to change the working directory before running the test command, which will avoid introducing subshells in the test code. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Apr 18, 2019 at 06:16 UTC 6ea18fffb016f7267f1f8bd2a4871500c4174f68
1 file changed +19
t/helper/test-tool.c
+19
@@ -1,5 +1,11 @@
1 #include "git-compat-util.h"
2 #include "test-tool.h"
3 +#include "parse-options.h"
4 +
5 +static const char * const test_tool_usage[] = {
6 + "test-tool [-C <directory>] <command [<arguments>...]]",
7 + NULL
8 +};
9
10 struct test_cmd {
11 const char *name;
@@ -73,11 +79,24 @@ static NORETURN void die_usage(void)
79 int cmd_main(int argc, const char **argv)
80 {
81 int i;
82 + const char *working_directory = NULL;
83 + struct option options[] = {
84 + OPT_STRING('C', NULL, &working_directory, "directory",
85 + "change the working directory"),
86 + OPT_END()
87 + };
88
89 BUG_exit_code = 99;
90 + argc = parse_options(argc, argv, NULL, options, test_tool_usage,
91 + PARSE_OPT_STOP_AT_NON_OPTION |
92 + PARSE_OPT_KEEP_ARGV0);
93 +
94 if (argc < 2)
95 die_usage();
96
97 + if (working_directory && chdir(working_directory) < 0)
98 + die("Could not cd to '%s'", working_directory);
99 +
100 for (i = 0; i < ARRAY_SIZE(cmds); i++) {
101 if (!strcmp(cmds[i].name, argv[1])) {
102 argv++;