mingw: optionally redirect stderr/stdout via the same handle
authorJohannes Schindelin <johannes.schindelin@gmx.de>
Wed, 1 Nov 2017 17:10:30 +0000 (18:10 +0100)
committerJunio C Hamano <gitster@pobox.com>
Thu, 2 Nov 2017 02:19:43 +0000 (11:19 +0900)
The "2>&1" notation in Powershell and in Unix shells implies that stderr
is redirected to the same handle into which stdout is already written.

Let's use this special value to allow the same trick with
GIT_REDIRECT_STDERR and GIT_REDIRECT_STDOUT: if the former's value is
`2>&1`, then stderr will simply be written to the same handle as stdout.

The functionality was suggested by Jeff Hostetler.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
compat/mingw.c
t/t0001-init.sh
index 6c6c7795a70fe2a95c8a95ee04f1895c3ed979ff..2d44d21aca8d31f67b16cb9a90245b4db526ff76 100644 (file)
@@ -2160,6 +2160,21 @@ static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
                        CloseHandle(handle);
                return;
        }
+       if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
+               handle = GetStdHandle(STD_OUTPUT_HANDLE);
+               if (handle == INVALID_HANDLE_VALUE) {
+                       close(fd);
+                       handle = GetStdHandle(std_id);
+                       if (handle != INVALID_HANDLE_VALUE)
+                               CloseHandle(handle);
+               } else {
+                       int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
+                       SetStdHandle(std_id, handle);
+                       dup2(new_fd, fd);
+                       /* do *not* close the new_fd: that would close stdout */
+               }
+               return;
+       }
        handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
                             flags, NULL);
        if (handle != INVALID_HANDLE_VALUE) {
index 0fd2fc453854794919b507a90608b1e5f7670ce1..c413bff9cf1f3a79ef494b39844c42d3a8c877f1 100755 (executable)
@@ -456,7 +456,13 @@ test_expect_success 're-init from a linked worktree' '
 test_expect_success MINGW 'redirect std handles' '
        GIT_REDIRECT_STDOUT=output.txt git rev-parse --git-dir &&
        test .git = "$(cat output.txt)" &&
-       test -z "$(GIT_REDIRECT_STDOUT=off git rev-parse --git-dir)"
+       test -z "$(GIT_REDIRECT_STDOUT=off git rev-parse --git-dir)" &&
+       test_must_fail env \
+               GIT_REDIRECT_STDOUT=output.txt \
+               GIT_REDIRECT_STDERR="2>&1" \
+               git rev-parse --git-dir --verify refs/invalid &&
+       printf ".git\nfatal: Needed a single revision\n" >expect &&
+       test_cmp expect output.txt
 '
 
 test_done