1 # Copyright(c) 2009, Gentoo Foundation
3 # Licensed under the GNU General Public License, v2
7 """Gentoo package query tool"""
9 from __future__ import print_function
13 'format_package_names',
16 __docformat__ = 'epytext'
17 # version is dynamically set by distutils sdist
28 from getopt import getopt, GetoptError
33 from gentoolkit import CONFIG
34 from gentoolkit import errors
35 from gentoolkit import pprinter as pp
36 from gentoolkit.textwrap_ import TextWrapper
38 __productname__ = "equery"
40 'Karl Trygve Kalleberg - Original author',
41 'Douglas Anderson - 0.3.0 author'
69 def print_help(with_description=True):
70 """Print description, usage and a detailed help message.
72 @param with_description (bool): Option to print module's __doc__ or not
79 print(pp.globaloption("global options"))
80 print(format_options((
81 (" -h, --help", "display this help message"),
82 (" -q, --quiet", "minimal output"),
83 (" -C, --no-color", "turn off colors"),
84 (" -N, --no-pipe", "turn off pipe detection"),
85 (" -V, --version", "display version info")
88 print(pp.command("modules") + " (" + pp.command("short name") + ")")
89 print(format_options((
90 (" (b)elongs", "list what package FILES belong to"),
91 (" (c)hanges", "list changelog entries for ATOM"),
92 (" chec(k)", "verify checksums and timestamps for PKG"),
93 (" (d)epends", "list all packages directly depending on ATOM"),
94 (" dep(g)raph", "display a tree of all dependencies for PKG"),
95 (" (f)iles", "list all files installed by PKG"),
96 (" h(a)s", "list all packages for matching ENVIRONMENT data stored in /var/db/pkg"),
97 (" (h)asuse", "list all packages that have USE flag"),
98 (" ke(y)words", "display keywords for specified PKG"),
99 (" (l)ist", "list package matching PKG"),
100 (" (m)eta", "display metadata about PKG"),
101 (" (s)ize", "display total size of all files owned by PKG"),
102 (" (u)ses", "display USE flags for PKG"),
103 (" (w)hich", "print full path to ebuild for PKG")
107 def expand_module_name(module_name):
108 """Returns one of the values of NAME_MAP or raises KeyError"""
110 if module_name == 'list':
111 # list is a Python builtin type, so we must rename our module
113 elif module_name in NAME_MAP.values():
116 return NAME_MAP[module_name]
119 def format_options(options):
120 """Format module options.
123 @param options: [('option 1', 'description 1'), ('option 2', 'des... )]
125 @return: formatted options string
129 twrap = TextWrapper(width=CONFIG['termWidth'])
130 opts = (x[0] for x in options)
131 descs = (x[1] for x in options)
132 for opt, desc in zip(opts, descs):
133 twrap.initial_indent = pp.emph(opt.ljust(25))
134 twrap.subsequent_indent = " " * 25
135 result.append(twrap.fill(desc))
137 return '\n'.join(result)
140 def format_filetype(path, fdesc, show_type=False, show_md5=False,
141 show_timestamp=False):
142 """Format a path for printing.
145 @param path: the path
147 @param fdesc: [file_type, timestamp, MD5 sum/symlink target]
148 file_type is one of dev, dir, obj, sym.
149 If file_type is dir, there is no timestamp or MD5 sum.
150 If file_type is sym, fdesc[2] is the target of the symlink.
151 @type show_type: bool
152 @param show_type: if True, prepend the file's type to the formatted string
154 @param show_md5: if True, append MD5 sum to the formatted string
155 @type show_timestamp: bool
156 @param show_timestamp: if True, append time-of-creation after pathname
158 @return: formatted pathname with optional added information
161 ftype = fpath = stamp = md5sum = ""
163 if fdesc[0] == "obj":
166 stamp = format_timestamp(fdesc[1])
168 elif fdesc[0] == "dir":
170 fpath = pp.path(path)
171 elif fdesc[0] == "sym":
173 stamp = format_timestamp(fdesc[1])
174 tgt = fdesc[2].split()[0]
178 fpath = pp.path_symlink(path + " -> " + tgt)
179 elif fdesc[0] == "dev":
184 pp.error("%s has unknown type: %s" % (path, fdesc[0]))
189 result += "%4s " % ftype
192 result += " " + stamp
194 result += " " + md5sum
199 def format_timestamp(timestamp):
200 """Format a timestamp into, e.g., '2009-01-31 21:19:44' format"""
202 return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(timestamp)))
205 def initialize_configuration():
206 """Setup the standard equery config"""
209 term_width = pp.output.get_term_size()[1]
211 # get_term_size() failed. Set a sane default width:
214 # Terminal size, minus a 1-char margin for text wrapping
215 CONFIG['termWidth'] = term_width - 1
218 if (CONFIG['color'] == -1 and (not sys.stdout.isatty() or
219 os.getenv("NOCOLOR") in ("yes", "true")) or CONFIG['color'] == 0):
223 CONFIG['verbose'] = False
224 # set extra wide, should disable wrapping unless
225 # there is some extra long text
226 CONFIG['termWidth'] = 600
228 CONFIG['debug'] = bool(os.getenv('DEBUG', False))
232 """Return the main usage message for equery"""
234 return "%(usage)s %(product)s [%(g_opts)s] %(mod_name)s [%(mod_opts)s]" % {
235 'usage': pp.emph("Usage:"),
236 'product': pp.productname(__productname__),
237 'g_opts': pp.globaloption("global-options"),
238 'mod_name': pp.command("module-name"),
239 'mod_opts': pp.localoption("module-options")
243 def mod_usage(mod_name="module", arg="pkgspec", optional=False):
244 """Provide a consistent usage message to the calling module.
247 @param arg: what kind of argument the module takes (pkgspec, filename, etc)
249 @param optional: is the argument optional?
252 return "%(usage)s: %(mod_name)s [%(opts)s] %(arg)s" % {
253 'usage': pp.emph("Usage"),
254 'mod_name': pp.command(mod_name),
255 'opts': pp.localoption("options"),
256 'arg': ("[%s]" % pp.emph(arg)) if optional else pp.emph(arg)
260 def parse_global_options(global_opts, args):
261 """Parse global input args and return True if we should display help for
262 the called module, else False (or display help and exit from here).
266 opts = (opt[0] for opt in global_opts)
268 if opt in ('-h', '--help'):
274 elif opt in ('-q','--quiet'):
275 CONFIG['quiet'] = True
276 elif opt in ('-C', '--no-color', '--nocolor'):
279 elif opt in ('-N', '--no-pipe'):
280 CONFIG['piping'] = False
281 elif opt in ('-V', '--version'):
284 elif opt in ('--debug'):
285 CONFIG['debug'] = True
291 """Print the version of this tool to the console."""
293 print("%(product)s (%(version)s) - %(docstring)s" % {
294 "product": pp.productname(__productname__),
295 "version": __version__,
300 def split_arguments(args):
301 """Separate module name from module arguments"""
303 return args.pop(0), args
307 """Parse input and run the program."""
311 'help', 'quiet', 'nocolor', 'no-color', 'no-pipe', 'version', 'debug'
314 initialize_configuration()
317 global_opts, args = getopt(sys.argv[1:], short_opts, long_opts)
318 except GetoptError as err:
319 sys.stderr.write(pp.error("Global %s" % err))
320 print_help(with_description=False)
323 # Parse global options
324 need_help = parse_global_options(global_opts, args)
326 # verbose is shorthand for the very common 'not quiet or piping'
327 if CONFIG['quiet'] or CONFIG['piping']:
328 CONFIG['verbose'] = False
330 CONFIG['verbose'] = True
333 module_name, module_args = split_arguments(args)
339 module_args.append('--help')
342 expanded_module_name = expand_module_name(module_name)
344 sys.stderr.write(pp.error("Unknown module '%s'" % module_name))
345 print_help(with_description=False)
349 loaded_module = __import__(
350 expanded_module_name, globals(), locals(), [], -1
352 loaded_module.main(module_args)
353 except portage.exception.AmbiguousPackageName as err:
354 raise errors.GentoolkitAmbiguousPackage(err.args[0])
355 except IOError as err:
356 if err.errno != errno.EPIPE:
359 if __name__ == '__main__':