Debian Codegraph @

autopage/command.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import abc
14 import collections
15 import collections.abc
16 import os
17 import sys
18
19 import typing
20 from typing import Optional, Dict, List
21
22
23 __all__ = ['DefaultPager', 'UserSpecifiedPager', 'PlatformPager',
24 'CustomPager',
25 'More', 'Less', 'LV']
26
27
28 PagerConfig = collections.namedtuple('PagerConfig', [
29 'color',
30 'line_buffering_requested',
31 'reset_terminal',
32 ])
33
34
35 class PagerCommand(metaclass=abc.ABCMeta):
36 """
37 Abstract base class for pager commands.
38
39 A subclass implementing this interface can be used to specify a particular
40 pager command to run and its environment.
41 """
42
43 @abc.abstractmethod
44 def command(self) -> List[str]:
45 """Return the list of command arguments."""
46 return ['more']
47
48 @abc.abstractmethod
49 def environment_variables(self,
50 config: PagerConfig) -> Optional[Dict[str, str]]:
51 """Return the dict of any environment variables to set."""
52 return None
53
54
55 class More(PagerCommand):
56 """The pager command ``more``."""
57
58 def command(self) -> List[str]:
59 if sys.platform.startswith('win32'):
60 return ['more.com']
61 return ['more']
62
63 def environment_variables(self,
64 config: PagerConfig) -> Optional[Dict[str, str]]:
65 return None
66
67
68 class Less(PagerCommand):
69 """The pager command ``less``."""
70
71 def command(self) -> List[str]:
72 return ['less']
73
74 def environment_variables(self,
75 config: PagerConfig) -> Optional[Dict[str, str]]:
76 flags = []
77 if config.color:
78 # This option will cause less to output ANSI color escape sequences
79 # in raw form.
80 # Equivalent to the --RAW-CONTROL-CHARS argument
81 flags.append('R')
82 if not config.line_buffering_requested and not config.reset_terminal:
83 # This option will cause less to buffer until an entire screen's
84 # worth of data is available (or the EOF is reached), so don't
85 # enable it when line buffering is explicitly requested. It also
86 # does not reset the terminal after exiting, so don't enable it
87 # when resetting the terminal is requested.
88 # Equivalent to the --quit-if-one-screen argument
89 flags.append('F')
90 if not config.reset_terminal:
91 # This option will cause less to not reset the terminal after
92 # exiting.
93 # Equivalent to the --no-init argument
94 flags.append('X')
95
96 if flags and (os.getenv('LESS') is None):
97 return {
98 'LESS': ''.join(flags)
99 }
100 return None
101
102
103 class LV(PagerCommand):
104 """The pager command ``lv``."""
105
106 def command(self) -> List[str]:
107 return ['lv']
108
109 def environment_variables(self,
110 config: PagerConfig) -> Optional[Dict[str, str]]:
111 if config.color and (os.getenv('LV') is None):
112 return {
113 # This option allows ANSI color escape sequences in lv
114 'LV': '-c',
115 }
116 return None
117
118
119 class CustomPager(PagerCommand):
120 """A pager command parsed from a user-specified string."""
121 def __init__(self, pager_cmdline: str):
122 import shlex
123 self._cmd = shlex.split(pager_cmdline)
124
125 def command(self) -> List[str]:
126 return self._cmd
127
128 def environment_variables(self,
129 config: PagerConfig) -> Optional[Dict[str, str]]:
130 env = {}
131 for cmd_provider in (Less, LV):
132 cmd_env = cmd_provider().environment_variables(config)
133 if cmd_env:
134 env.update(cmd_env)
135 return env or None
136
137
138 def PlatformPager() -> PagerCommand:
139 """
140 Return the default pager command for the current platform.
141 """
142 if sys.platform.startswith('aix'):
143 return More()
144 if sys.platform.startswith('win32'):
145 return More()
146 return Less()
147
148
149 def UserSpecifiedPager(*env_vars: str) -> PagerCommand:
150 """
151 Return the pager command for the current environment.
152
153 Each of the specified environment variables is searched in order; the first
154 one that is set will be used as the pager command. If none of the
155 environment variables is set, the default pager for the platform will be
156 used.
157 """
158 for env_var in env_vars:
159 env_pager = os.getenv(env_var)
160 if env_pager:
161 return CustomPager(env_pager)
162 return PlatformPager()
163
164
165 def DefaultPager() -> PagerCommand:
166 """
167 Return the default pager command for the current environment.
168
169 If there is a $PAGER environment variable configured, this command will be
170 used. Otherwise, the default pager for the platform will be used.
171 """
172
173 if os.name == 'posix':
174 # Check that we are not running with elevated privileges
175 if os.getuid() not in {0, os.geteuid()}:
176 return PlatformPager()
177 return UserSpecifiedPager('PAGER')
178
179
180 CommandType = typing.Union[PagerCommand,
181 typing.Callable[[], PagerCommand],
182 str,
183 typing.Sequence[str]]
184
185
186 def get_pager_command(pager_command: CommandType) -> PagerCommand:
187 if isinstance(pager_command, PagerCommand):
188 return pager_command
189
190 if isinstance(pager_command, str):
191 return CustomPager(pager_command)
192
193 if isinstance(pager_command, collections.abc.Sequence):
194 return UserSpecifiedPager(*pager_command)
195
196 if callable(pager_command):
197 cmd = pager_command()
198 if isinstance(cmd, PagerCommand):
199 return cmd
200
201 raise TypeError('Invalid type for ``pager_command``')