Debian Codegraph @

lib/contrib/which/which.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) 2002-2005 ActiveState Corp.
3 # See LICENSE.txt for license details.
4 # Author:
5 # Trent Mick ([email protected])
6 # Home:
7 # http://trentm.com/projects/which/
8 from __future__ import print_function
9
10
11 r"""Find the full path to commands.
12
13 which(command, path=None, verbose=0, exts=None)
14 Return the full path to the first match of the given command on the
15 path.
16
17 whichall(command, path=None, verbose=0, exts=None)
18 Return a list of full paths to all matches of the given command on
19 the path.
20
21 whichgen(command, path=None, verbose=0, exts=None)
22 Return a generator which will yield full paths to all matches of the
23 given command on the path.
24
25 By default the PATH environment variable is searched (as well as, on
26 Windows, the AppPaths key in the registry), but a specific 'path' list
27 to search may be specified as well. On Windows, the PATHEXT environment
28 variable is applied as appropriate.
29
30 If "verbose" is true then a tuple of the form
31 (<fullpath>, <matched-where-description>)
32 is returned for each match. The latter element is a textual description
33 of where the match was found. For example:
34 from PATH element 0
35 from HKLM\SOFTWARE\...\perl.exe
36 """
37
38 _cmdlnUsage = """
39 Show the full path of commands.
40
41 Usage:
42 which [<options>...] [<command-name>...]
43
44 Options:
45 -h, --help Print this help and exit.
46 -V, --version Print the version info and exit.
47
48 -a, --all Print *all* matching paths.
49 -v, --verbose Print out how matches were located and
50 show near misses on stderr.
51 -q, --quiet Just print out matches. I.e., do not print out
52 near misses.
53
54 -p <altpath>, --path=<altpath>
55 An alternative path (list of directories) may
56 be specified for searching.
57 -e <exts>, --exts=<exts>
58 Specify a list of extensions to consider instead
59 of the usual list (';'-separate list, Windows
60 only).
61
62 Show the full path to the program that would be run for each given
63 command name, if any. Which, like GNU's which, returns the number of
64 failed arguments, or -1 when no <command-name> was given.
65
66 Near misses include duplicates, non-regular files and (on Un*x)
67 files without executable access.
68 """
69
70 __revision__ = "$Id$"
71 __version_info__ = (1, 1, 0)
72 __version__ = '.'.join(map(str, __version_info__))
73
74 import os
75 import sys
76 import getopt
77 import stat
78
79
80 #---- exceptions
81
82 class WhichError(Exception):
83 pass
84
85
86
87 #---- internal support stuff
88
89 def _getRegisteredExecutable(exeName):
90 """Windows allow application paths to be registered in the registry."""
91 registered = None
92 if sys.platform.startswith('win'):
93 if os.path.splitext(exeName)[1].lower() != '.exe':
94 exeName += '.exe'
95 import _winreg
96 try:
97 key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\
98 exeName
99 value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, key)
100 registered = (value, "from HKLM\\"+key)
101 except _winreg.error:
102 pass
103 if registered and not os.path.exists(registered[0]):
104 registered = None
105 return registered
106
107 def _samefile(fname1, fname2):
108 if sys.platform.startswith('win'):
109 return ( os.path.normpath(os.path.normcase(fname1)) ==\
110 os.path.normpath(os.path.normcase(fname2)) )
111 else:
112 return os.path.samefile(fname1, fname2)
113
114 def _cull(potential, matches, verbose=0):
115 """Cull inappropriate matches. Possible reasons:
116 - a duplicate of a previous match
117 - not a disk file
118 - not executable (non-Windows)
119 If 'potential' is approved it is returned and added to 'matches'.
120 Otherwise, None is returned.
121 """
122 for match in matches: # don't yield duplicates
123 if _samefile(potential[0], match[0]):
124 if verbose:
125 sys.stderr.write("duplicate: %s (%s)\n" % potential)
126 return None
127 else:
128 if not stat.S_ISREG(os.stat(potential[0]).st_mode):
129 if verbose:
130 sys.stderr.write("not a regular file: %s (%s)\n" % potential)
131 elif not os.access(potential[0], os.X_OK):
132 if verbose:
133 sys.stderr.write("no executable access: %s (%s)\n"\
134 % potential)
135 else:
136 matches.append(potential)
137 return potential
138
139
140 #---- module API
141
142 def whichgen(command, path=None, verbose=0, exts=None):
143 """Return a generator of full paths to the given command.
144
145 "command" is a the name of the executable to search for.
146 "path" is an optional alternate path list to search. The default it
147 to use the PATH environment variable.
148 "verbose", if true, will cause a 2-tuple to be returned for each
149 match. The second element is a textual description of where the
150 match was found.
151 "exts" optionally allows one to specify a list of extensions to use
152 instead of the standard list for this system. This can
153 effectively be used as an optimization to, for example, avoid
154 stat's of "foo.vbs" when searching for "foo" and you know it is
155 not a VisualBasic script but ".vbs" is on PATHEXT. This option
156 is only supported on Windows.
157
158 This method returns a generator which yields either full paths to
159 the given command or, if verbose, tuples of the form (<path to
160 command>, <where path found>).
161 """
162 matches = []
163 if path is None:
164 usingGivenPath = 0
165 path = os.environ.get("PATH", "").split(os.pathsep)
166 if sys.platform.startswith("win"):
167 path.insert(0, os.curdir) # implied by Windows shell
168 else:
169 usingGivenPath = 1
170
171 # Windows has the concept of a list of extensions (PATHEXT env var).
172 if sys.platform.startswith("win"):
173 if exts is None:
174 exts = os.environ.get("PATHEXT", "").split(os.pathsep)
175 # If '.exe' is not in exts then obviously this is Win9x and
176 # or a bogus PATHEXT, then use a reasonable default.
177 for ext in exts:
178 if ext.lower() == ".exe":
179 break
180 else:
181 exts = ['.COM', '.EXE', '.BAT']
182 elif not isinstance(exts, list):
183 raise TypeError("'exts' argument must be a list or None")
184 else:
185 if exts is not None:
186 raise WhichError("'exts' argument is not supported on "\
187 "platform '%s'" % sys.platform)
188 exts = []
189
190 # File name cannot have path separators because PATH lookup does not
191 # work that way.
192 if os.sep in command or os.altsep and os.altsep in command:
193 pass
194 else:
195 for i in range(len(path)):
196 dirName = path[i]
197 # On windows the dirName *could* be quoted, drop the quotes
198 if sys.platform.startswith("win") and len(dirName) >= 2\
199 and dirName[0] == '"' and dirName[-1] == '"':
200 dirName = dirName[1:-1]
201 for ext in ['']+exts:
202 absName = os.path.abspath(
203 os.path.normpath(os.path.join(dirName, command+ext)))
204 if os.path.isfile(absName):
205 if usingGivenPath:
206 fromWhere = "from given path element %d" % i
207 elif not sys.platform.startswith("win"):
208 fromWhere = "from PATH element %d" % i
209 elif i == 0:
210 fromWhere = "from current directory"
211 else:
212 fromWhere = "from PATH element %d" % (i-1)
213 match = _cull((absName, fromWhere), matches, verbose)
214 if match:
215 if verbose:
216 yield match
217 else:
218 yield match[0]
219 match = _getRegisteredExecutable(command)
220 if match is not None:
221 match = _cull(match, matches, verbose)
222 if match:
223 if verbose:
224 yield match
225 else:
226 yield match[0]
227
228
229 def which(command, path=None, verbose=0, exts=None):
230 """Return the full path to the first match of the given command on
231 the path.
232
233 "command" is a the name of the executable to search for.
234 "path" is an optional alternate path list to search. The default it
235 to use the PATH environment variable.
236 "verbose", if true, will cause a 2-tuple to be returned. The second
237 element is a textual description of where the match was found.
238 "exts" optionally allows one to specify a list of extensions to use
239 instead of the standard list for this system. This can
240 effectively be used as an optimization to, for example, avoid
241 stat's of "foo.vbs" when searching for "foo" and you know it is
242 not a VisualBasic script but ".vbs" is on PATHEXT. This option
243 is only supported on Windows.
244
245 If no match is found for the command, a WhichError is raised.
246 """
247 try:
248 match = next(whichgen(command, path, verbose, exts))
249 except StopIteration:
250 raise WhichError("Could not find '%s' on the path." % command)
251 return match
252
253
254 def whichall(command, path=None, verbose=0, exts=None):
255 """Return a list of full paths to all matches of the given command
256 on the path.
257
258 "command" is a the name of the executable to search for.
259 "path" is an optional alternate path list to search. The default it
260 to use the PATH environment variable.
261 "verbose", if true, will cause a 2-tuple to be returned for each
262 match. The second element is a textual description of where the
263 match was found.
264 "exts" optionally allows one to specify a list of extensions to use
265 instead of the standard list for this system. This can
266 effectively be used as an optimization to, for example, avoid
267 stat's of "foo.vbs" when searching for "foo" and you know it is
268 not a VisualBasic script but ".vbs" is on PATHEXT. This option
269 is only supported on Windows.
270 """
271 return list( whichgen(command, path, verbose, exts) )
272
273
274
275 #---- mainline
276
277 def main(argv):
278 all = 0
279 verbose = 0
280 altpath = None
281 exts = None
282 try:
283 optlist, args = getopt.getopt(argv[1:], 'haVvqp:e:',
284 ['help', 'all', 'version', 'verbose', 'quiet', 'path=', 'exts='])
285 except getopt.GetoptError as msg:
286 sys.stderr.write("which: error: %s. Your invocation was: %s\n"\
287 % (msg, argv))
288 sys.stderr.write("Try 'which --help'.\n")
289 return 1
290 for opt, optarg in optlist:
291 if opt in ('-h', '--help'):
292 print(_cmdlnUsage)
293 return 0
294 elif opt in ('-V', '--version'):
295 print("which %s" % __version__)
296 return 0
297 elif opt in ('-a', '--all'):
298 all = 1
299 elif opt in ('-v', '--verbose'):
300 verbose = 1
301 elif opt in ('-q', '--quiet'):
302 verbose = 0
303 elif opt in ('-p', '--path'):
304 if optarg:
305 altpath = optarg.split(os.pathsep)
306 else:
307 altpath = []
308 elif opt in ('-e', '--exts'):
309 if optarg:
310 exts = optarg.split(os.pathsep)
311 else:
312 exts = []
313
314 if len(args) == 0:
315 return -1
316
317 failures = 0
318 for arg in args:
319 #print "debug: search for %r" % arg
320 nmatches = 0
321 for match in whichgen(arg, path=altpath, verbose=verbose, exts=exts):
322 if verbose:
323 print("%s (%s)" % match)
324 else:
325 print(match)
326 nmatches += 1
327 if not all:
328 break
329 if not nmatches:
330 failures += 1
331 return failures
332
333
334 if __name__ == "__main__":
335 sys.exit( main(sys.argv) )
336
337