blob: 888b108b4c9fdc44a3e7d4b3e88b471b065a0ac4 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001#
2# Copyright (C) 2008 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os
17import select
18import sys
19
20active = False
21
22def RunPager(globalConfig):
23 global active
24
Shawn O. Pearce8f82a4f2009-04-01 07:24:22 -070025 if not os.isatty(0) or not os.isatty(1):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026 return
27 pager = _SelectPager(globalConfig)
28 if pager == '' or pager == 'cat':
29 return
30
31 # This process turns into the pager; a child it forks will
32 # do the real processing and output back to the pager. This
33 # is necessary to keep the pager in control of the tty.
34 #
35 try:
36 r, w = os.pipe()
37 pid = os.fork()
38 if not pid:
39 os.dup2(w, 1)
40 os.dup2(w, 2)
41 os.close(r)
42 os.close(w)
43 active = True
44 return
45
46 os.dup2(r, 0)
47 os.close(r)
48 os.close(w)
49
50 _BecomePager(pager)
51 except Exception:
52 print >>sys.stderr, "fatal: cannot start pager '%s'" % pager
David Pursehouse01f443d2012-10-03 19:11:28 +090053 sys.exit(255)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070054
55def _SelectPager(globalConfig):
56 try:
57 return os.environ['GIT_PAGER']
58 except KeyError:
59 pass
60
61 pager = globalConfig.GetString('core.pager')
62 if pager:
63 return pager
64
65 try:
66 return os.environ['PAGER']
67 except KeyError:
68 pass
69
70 return 'less'
71
72def _BecomePager(pager):
73 # Delaying execution of the pager until we have output
74 # ready works around a long-standing bug in popularly
75 # available versions of 'less', a better 'more'.
76 #
David Pursehouse8a68ff92012-09-24 12:15:13 +090077 _a, _b, _c = select.select([0], [], [0])
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070078
79 os.environ['LESS'] = 'FRSX'
80
81 try:
82 os.execvp(pager, [pager])
David Pursehouse8a68ff92012-09-24 12:15:13 +090083 except OSError:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070084 os.execv('/bin/sh', ['sh', '-c', pager])