man page updates thanks to Francesco Turco. Update analyze and rebuild modules...
[gentoolkit.git] / pym / gentoolkit / base.py
1 #!/usr/bin/python
2 #
3 # Copyright(c) 2009 - 2010, Gentoo Foundation
4 # Distributed under the terms of the GNU General Public License v2
5 #
6 # $Header: $
7
8 """Gentoolkit Base Module class to hold common module operation functions
9 """
10
11 from __future__ import print_function
12
13 __docformat__ = 'epytext'
14
15
16 import errno
17 import os
18 import sys
19 import time
20 from getopt import gnu_getopt, GetoptError
21
22 import gentoolkit
23 from gentoolkit import errors
24 #from gentoolkit.textwrap_ import TextWrapper
25 import gentoolkit.pprinter as pp
26 from gentoolkit.formatters import format_options
27
28
29 GLOBAL_OPTIONS = (
30         ("    -h, --help", "display this help message"),
31         ("    -q, --quiet", "minimal output"),
32         ("    -C, --no-color", "turn off colors"),
33         ("    -N, --no-pipe", "turn off pipe detection"),
34         ("    -V, --version", "display version info")
35 )
36
37
38 def initialize_configuration():
39         """Setup the standard equery config"""
40
41         # Get terminal size
42         term_width = pp.output.get_term_size()[1]
43         if term_width < 1:
44                 # get_term_size() failed. Set a sane default width:
45                 term_width = 80
46         # Terminal size, minus a 1-char margin for text wrapping
47         gentoolkit.CONFIG['termWidth'] = term_width - 1
48         # Guess color output
49         if (gentoolkit.CONFIG['color'] == -1 and (not sys.stdout.isatty() or
50                 os.getenv("NOCOLOR") in ("yes", "true")) or gentoolkit.CONFIG['color'] == 0):
51                 pp.output.nocolor()
52         gentoolkit.CONFIG['verbose'] = not gentoolkit.CONFIG['piping']
53
54
55 def split_arguments(args):
56         """Separate module name from module arguments"""
57
58         return args.pop(0), args
59
60
61 def main_usage(module_info):
62         """Return the main usage message for analyse"""
63         return "%(usage)s %(product)s [%(g_opts)s] %(mod_name)s [%(mod_opts)s]" % {
64                 'usage': pp.emph("Usage:"),
65                 'product': pp.productname(module_info["__productname__"]),
66                 'g_opts': pp.globaloption("global-options"),
67                 'mod_name': pp.command("module-name"),
68                 'mod_opts': pp.localoption("module-options")
69         }
70
71
72 def print_version(module_info):
73         """Print the version of this tool to the console."""
74
75         print("%(product)s (%(version)s) - %(docstring)s" % {
76                 "product": pp.productname(module_info["__productname__"]),
77                 "version": module_info["__version__"],
78                 "docstring": module_info["__doc__"]
79         })
80
81
82 def print_help(module_info, formatted_options=None, with_description=True):
83         """Print description, usage and a detailed help message.
84
85         @param with_description (bool): Option to print module's __doc__ or not
86         """
87
88         if with_description:
89                 print()
90                 print(module_info["__doc__"])
91                 print()
92         print(main_usage(module_info))
93         print()
94         print(pp.globaloption("global options"))
95         print(format_options(GLOBAL_OPTIONS))
96         print()
97         if formatted_options:
98                 print(pp.command("modules") + " (" + pp.command("short name") + ")")
99                 print(format_options(formatted_options))
100         else:
101                 print("Error: calling function did not supply formatted options")
102                 print()
103
104
105 def parse_global_options(global_opts, args, module_info, formatted_options):
106         """Parse global input args and return True if we should display help for
107         the called module, else False (or display help and exit from here).
108         """
109
110         need_help = False
111         do_help = False
112         opts = (opt[0] for opt in global_opts)
113         for opt in opts:
114                 if opt in ('-h', '--help'):
115                         do_help = True
116                         if args:
117                                 need_help = True
118                         else:
119                                 do_help = True
120                 elif opt in ('-q','--quiet'):
121                         gentoolkit.CONFIG['quiet'] = True
122                 elif opt in ('-C', '--no-color', '--nocolor'):
123                         gentoolkit.CONFIG['color'] = 0
124                         pp.output.nocolor()
125                 elif opt in ('-N', '--no-pipe'):
126                         gentoolkit.CONFIG['piping'] = False
127                 elif opt in ('-V', '--version'):
128                         print_version(module_info)
129                         sys.exit(0)
130                 elif opt in ('--debug'):
131                         gentoolkit.CONFIG['debug'] = True
132         if do_help:
133                 print_help( module_info, formatted_options)
134                 sys.exit(0)
135         return need_help
136
137
138 def mod_usage(mod_name="module", arg="pkgspec", optional=False):
139         """Provide a consistant usage message to the calling module.
140
141         @type arg: string
142         @param arg: what kind of argument the module takes (pkgspec, filename, etc)
143         @type optional: bool
144         @param optional: is the argument optional?
145         """
146
147         return "%(usage)s: %(mod_name)s [%(opts)s] %(arg)s" % {
148                 'usage': pp.emph("Usage"),
149                 'mod_name': pp.command(mod_name),
150                 'opts': pp.localoption("options"),
151                 'arg': ("[%s]" % pp.emph(arg)) if optional else pp.emph(arg)
152         }
153