1#include "cache.h"
2#include "run-command.h"
3#include "sigchain.h"
4
5#ifndef DEFAULT_PAGER
6#define DEFAULT_PAGER "less"
7#endif
8
9/*
10 * This is split up from the rest of git so that we can do
11 * something different on Windows.
12 */
13
14#ifndef WIN32
15static void pager_preexec(void)
16{
17 /*
18 * Work around bug in "less" by not starting it until we
19 * have real input
20 */
21 fd_set in;
22
23 FD_ZERO(&in);
24 FD_SET(0, &in);
25 select(1, &in, NULL, &in, NULL);
26}
27#endif
28
29static const char *pager_argv[] = { NULL, NULL };
30static struct child_process pager_process;
31
32static void wait_for_pager(void)
33{
34 fflush(stdout);
35 fflush(stderr);
36 /* signal EOF to pager */
37 close(1);
38 close(2);
39 finish_command(&pager_process);
40}
41
42static void wait_for_pager_signal(int signo)
43{
44 wait_for_pager();
45 sigchain_pop(signo);
46 raise(signo);
47}
48
49const char *git_pager(int stdout_is_tty)
50{
51 const char *pager;
52
53 if (!stdout_is_tty)
54 return NULL;
55
56 pager = getenv("GIT_PAGER");
57 if (!pager) {
58 if (!pager_program)
59 git_config(git_default_config, NULL);
60 pager = pager_program;
61 }
62 if (!pager)
63 pager = getenv("PAGER");
64 if (!pager)
65 pager = DEFAULT_PAGER;
66 else if (!*pager || !strcmp(pager, "cat"))
67 pager = NULL;
68
69 return pager;
70}
71
72void setup_pager(void)
73{
74 const char *pager = git_pager(isatty(1));
75
76 if (!pager)
77 return;
78
79 setenv("GIT_PAGER_IN_USE", "true", 1);
80
81 /* spawn the pager */
82 pager_argv[0] = pager;
83 pager_process.use_shell = 1;
84 pager_process.argv = pager_argv;
85 pager_process.in = -1;
86 if (!getenv("LESS")) {
87 static const char *env[] = { "LESS=FRSX", NULL };
88 pager_process.env = env;
89 }
90#ifndef WIN32
91 pager_process.preexec_cb = pager_preexec;
92#endif
93 if (start_command(&pager_process))
94 return;
95
96 /* original process continues, but writes to the pipe */
97 dup2(pager_process.in, 1);
98 if (isatty(2))
99 dup2(pager_process.in, 2);
100 close(pager_process.in);
101
102 /* this makes sure that the parent terminates after the pager */
103 sigchain_push_common(wait_for_pager_signal);
104 atexit(wait_for_pager);
105}
106
107int pager_in_use(void)
108{
109 const char *env;
110 env = getenv("GIT_PAGER_IN_USE");
111 return env ? git_config_bool("GIT_PAGER_IN_USE", env) : 0;
112}