Merge with js/unlink.
[git/mingw.git] / pager.c
blobd72c5e8d944eadd70e5ec69eeac583621288078f
1 #include "cache.h"
2 #include "spawn-pipe.h"
4 /*
5 * This is split up from the rest of git so that we might do
6 * something different on Windows, for example.
7 */
9 #ifndef __MINGW32__
10 static void run_pager(const char *pager)
12 execlp(pager, pager, NULL);
13 execl("/bin/sh", "sh", "-c", pager, NULL);
15 #else
16 static pid_t pager_pid;
17 static void collect_pager(void)
19 close(1); /* signals EOF to pager */
20 cwait(NULL, pager_pid, 0);
22 #endif
24 void setup_pager(void)
26 #ifndef __MINGW32__
27 pid_t pid;
28 #else
29 const char *pager_argv[] = { "sh", "-c", NULL, NULL };
30 #endif
31 int fd[2];
32 const char *pager = getenv("GIT_PAGER");
34 if (!isatty(1))
35 return;
36 if (!pager)
37 pager = getenv("PAGER");
38 if (!pager)
39 pager = "less";
40 else if (!*pager || !strcmp(pager, "cat"))
41 return;
43 pager_in_use = 1; /* means we are emitting to terminal */
45 if (pipe(fd) < 0)
46 return;
47 #ifndef __MINGW32__
48 pid = fork();
49 if (pid < 0) {
50 close(fd[0]);
51 close(fd[1]);
52 return;
55 /* return in the child */
56 if (!pid) {
57 dup2(fd[1], 1);
58 close(fd[0]);
59 close(fd[1]);
60 return;
63 /* The original process turns into the PAGER */
64 dup2(fd[0], 0);
65 close(fd[0]);
66 close(fd[1]);
68 setenv("LESS", "FRSX", 0);
69 run_pager(pager);
70 die("unable to execute pager '%s'", pager);
71 exit(255);
72 #else
73 /* spawn the pager */
74 pager_argv[2] = pager;
75 pager_pid = spawnvpe_pipe(pager_argv[0], pager_argv, environ, fd, NULL);
76 if (pager_pid < 0)
77 return;
79 /* original process continues, but writes to the pipe */
80 dup2(fd[1], 1);
81 close(fd[1]);
83 /* this makes sure that the parent terminates after the pager */
84 atexit(collect_pager);
85 #endif