832d902012cd3b34a7a3bae7a0bef8981d3902ed
[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         opts = (opt[0] for opt in global_opts)
112         for opt in opts:
113                 if opt in ('-h', '--help'):
114                         if args:
115                                 need_help = True
116                         else:
117                                 print_help( module_info, formatted_options)
118                                 sys.exit(0)
119                 elif opt in ('-q','--quiet'):
120                         gentoolkit.CONFIG['quiet'] = True
121                 elif opt in ('-C', '--no-color', '--nocolor'):
122                         gentoolkit.CONFIG['color'] = 0
123                         pp.output.nocolor()
124                 elif opt in ('-N', '--no-pipe'):
125                         gentoolkit.CONFIG['piping'] = False
126                 elif opt in ('-V', '--version'):
127                         print_version(module_info)
128                         sys.exit(0)
129                 elif opt in ('--debug'):
130                         gentoolkit.CONFIG['debug'] = True
131         return need_help
132
133
134 def mod_usage(mod_name="module", arg="pkgspec", optional=False):
135         """Provide a consistant usage message to the calling module.
136
137         @type arg: string
138         @param arg: what kind of argument the module takes (pkgspec, filename, etc)
139         @type optional: bool
140         @param optional: is the argument optional?
141         """
142
143         return "%(usage)s: %(mod_name)s [%(opts)s] %(arg)s" % {
144                 'usage': pp.emph("Usage"),
145                 'mod_name': pp.command(mod_name),
146                 'opts': pp.localoption("options"),
147                 'arg': ("[%s]" % pp.emph(arg)) if optional else pp.emph(arg)
148         }
149