pager.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #
  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. import os
  16. import select
  17. import sys
  18. active = False
  19. def RunPager(globalConfig):
  20. global active
  21. if not os.isatty(0):
  22. return
  23. pager = _SelectPager(globalConfig)
  24. if pager == '' or pager == 'cat':
  25. return
  26. # This process turns into the pager; a child it forks will
  27. # do the real processing and output back to the pager. This
  28. # is necessary to keep the pager in control of the tty.
  29. #
  30. try:
  31. r, w = os.pipe()
  32. pid = os.fork()
  33. if not pid:
  34. os.dup2(w, 1)
  35. os.dup2(w, 2)
  36. os.close(r)
  37. os.close(w)
  38. active = True
  39. return
  40. os.dup2(r, 0)
  41. os.close(r)
  42. os.close(w)
  43. _BecomePager(pager)
  44. except Exception:
  45. print >>sys.stderr, "fatal: cannot start pager '%s'" % pager
  46. os.exit(255)
  47. def _SelectPager(globalConfig):
  48. try:
  49. return os.environ['GIT_PAGER']
  50. except KeyError:
  51. pass
  52. pager = globalConfig.GetString('core.pager')
  53. if pager:
  54. return pager
  55. try:
  56. return os.environ['PAGER']
  57. except KeyError:
  58. pass
  59. return 'less'
  60. def _BecomePager(pager):
  61. # Delaying execution of the pager until we have output
  62. # ready works around a long-standing bug in popularly
  63. # available versions of 'less', a better 'more'.
  64. #
  65. a, b, c = select.select([0], [], [0])
  66. os.environ['LESS'] = 'FRSX'
  67. try:
  68. os.execvp(pager, [pager])
  69. except OSError, e:
  70. os.execv('/bin/sh', ['sh', '-c', pager])