This file is indexed.

/usr/share/pyshared/gnatpython/main.py is in python-gnatpython 54-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
 ############################################################################
 #                                                                          #
 #                              MAIN.PY                                     #
 #                                                                          #
 #           Copyright (C) 2008 - 2010 Ada Core Technologies, Inc.          #
 #                                                                          #
 # This program is free software: you can redistribute it and/or modify     #
 # it under the terms of the GNU General Public License as published by     #
 # the Free Software Foundation, either version 3 of the License, or        #
 # (at your option) any later version.                                      #
 #                                                                          #
 # This program is distributed in the hope that it will be useful,          #
 # but WITHOUT ANY WARRANTY; without even the implied warranty of           #
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
 # GNU General Public License for more details.                             #
 #                                                                          #
 # You should have received a copy of the GNU General Public License        #
 # along with this program.  If not, see <http://www.gnu.org/licenses/>     #
 #                                                                          #
 ############################################################################

"""Main program initialization

This package provides a class called Main used to initialize a python script
invoked from command line. The main goal is to ensure consistency in term of
interface, documentation and logging activities for all scripts using
gnatpython.

When a script uses this module, it should contain a docstring formatted in
the following way. Everything before the first empty line will be part of the
usage. Everything after will be considered as part of the description.

The script will support by default the following switches::

    --target     to set the target
    --host       to set the host
    -v|--verbose to enable verbose mode (a console logger is added)
    -h|--help    display information parsed in the docstring
    --log-file FILE
                 to redirect logs to a given file (this is independant from
                 verbose option

*EXAMPLES*

If you have the following script test.py::

    \"\"\"test [options] [args]

    This is the description\"\"\"

    import logging
    from gnatpython.main import *

    m = Main(add_targets_options=True)
    m.add_option("-t",
                 "--test",
                 dest="test",
                 metavar="STRING",
                 default="default",
                 help="option example")
    m.parse_args()
    logging.info('Test begin')
    logging.debug('test option value: ' + m.options.test)
    logging.debug('target option value: ' + m.options.target)
    logging.debug('host option value: ' + m.options.host)
    logging.info('Test end')

Here are some invocation examples::

    $ gnatpython test.py --help
    usage: test [options] [args]

    This is the description

    options:
      -h, --help            show this help message and exit
      -v, --verbose         add some verbosity for debugging purposes
      --target=TARGET       set target
      --host=HOST           set host
      -t STRING, --test=STRING
                            option example

    $ gnatpython test.py -v
    root        : INFO     Test begin
    root        : DEBUG    test option value: default
    root        : DEBUG    target option value:
    root        : DEBUG    host option value:
    root        : INFO     Test end

    $ gnatpython test.py
    root        : INFO     Test begin
    root        : INFO     Test end

"""
from optparse import OptionGroup, OptionParser, TitledHelpFormatter

import logging
import os
import re
import sys

import gnatpython.logging_util
from gnatpython.logging_util import (highlight, COLOR_RED, COLOR_YELLOW,
                                     COLOR_GREEN, COLOR_CYAN)
from gnatpython.env import Env


class MainError (Exception):
    """MainError exception"""
    pass


class MainHelpFormatter(TitledHelpFormatter):
    """Format help with underlined section headers.

    Do not modify description formatting.
    """

    def format_description(self, description):
        """Do not modify description"""
        return description

color_table = {
    ' (FAILED|DIFF)': COLOR_RED,
    ' (UOK)': COLOR_YELLOW,
    ' (OK|PASSED)': COLOR_GREEN,
    ' (XFAIL)': COLOR_RED,
    ' (DEAD)': COLOR_CYAN}


class ConsoleColorFormatter(logging.Formatter):
    """Formatter with color support

    REMARKS
      If level is ERROR or CRITICAL then the output color is set to red.
      Futhermore if some keyword such as PASSED,FAILED are detected then
      they are highlighted with an adequate color
    """

    def __init__(self, fmt=None, datefmt=None):
        logging.Formatter.__init__(self, fmt, datefmt)

    def format(self, record):
        output = logging.Formatter.format(self, record)
        if record.levelno >= logging.ERROR:
            output = highlight(output, fg=COLOR_RED)
        else:
            for k in color_table:
                output = re.sub(
                   k, ' ' + highlight("\\1", fg=color_table[k]), output)
        return output


class Main(object):
    """
    ATTRIBUTES
      name       : name of the program (default is the filename with the
                   extension)
      usage      : contains the usage retrived from the main docstring
      description: contains the description retrieved from the main docstring
      options    : object containing the result of option parsing (see python
                   optparse module). Note that this object is made global by
                   putting its value in Env.main_options.
      args       : list of positionnal parameters after processing options
      add_option : this is in fact a method that can be used to add other
                   options (see documentation of the Python module optparse)
    """

    def __init__(self, name=None, formatter=None,
                 require_docstring=True, add_targets_options=False):
        """Init Main object

        PARAMETERS
          name: name of the program (if not specified the filename without
                extension is taken)
          formatter: override the default formatter for console output
          require_docstring: if True, raise MainError when the toplevel
                             docstring is not found
          add_targets_options: add --target and --host options

        RETURN VALUE
          an instance of Main

        REMARKS
          None
        """
        main = sys.modules['__main__']

        if name is not None:
            self.name = name
        else:
            self.name = os.path.splitext(os.path.basename(main.__file__))[0]

        docstring = main.__doc__
        if require_docstring and docstring is None:
            raise MainError('Doc string not found')

        if docstring is not None:
            usage_end = docstring.find('\n\n')
            if usage_end == -1 and require_docstring:
                raise MainError('Doc string must start with a usage,'
                                'followed by an empty line')

        if docstring is not None:
            self.usage = docstring[0:usage_end]
            self.description = docstring[usage_end + 2:]
        else:
            self.usage = ""
            self.description = ""
        self.add_targets_options = add_targets_options

        self.__option_parser = OptionParser(
            usage=self.usage,
            description=self.description,
            formatter=MainHelpFormatter())

        # Make the add_option function directly available to Main objects
        self.add_option = self.__option_parser.add_option

        # And export add_option_group
        log_options = self.create_option_group("Various logging options")

        log_options.add_option(
            "-v", "--verbose",
            dest="verbose",
            action="store_true",
            default=False,
            help="add some verbosity for debugging purposes. "
            + "Overrides --loglevel")
        log_options.add_option(
            "--log-file",
            dest="logfile",
            metavar="FILE",
            default="",
            help="add some logs into the specified file")
        log_options.add_option(
            "--enable-color",
            dest="enable_color",
            action="store_true",
            default=False,
            help="enable colors in log outputs")
        log_options.add_option(
            "--loglevel", default="INFO",
            action="store",
            help="defines a loglevel (RAW,DEBUG,INFO,ERROR) for"
            + " stdout")

        self.add_option_group(log_options)

        if add_targets_options:
            self.add_option("--target",
                            dest="target",
                            metavar="TARGET[,TARGET_VERSION[,TARGET_MACHINE]]",
                            default="",
                            help="set target")
            self.add_option("--host",
                            dest="host",
                            metavar="HOST[,HOST_VERSION]",
                            default="",
                            help="set host")
        self.options = None
        self.args = None
        self.formatter = formatter
        self.__log_handlers_set = False

        # By default do not filter anything. What is effectively logged will
        # be defined by setting/unsetting handlers
        logging.getLogger('').setLevel(gnatpython.logging_util.RAW)

    def disable_interspersed_args(self):
        """See optparse.disable_interspersed_args in standard python library"""

        self.__option_parser.disable_interspersed_args()

    def parse_args(self, args=None):
        """Parse options and set console logger

        PARAMETERS
          args: the list of positional parameters. If None then sys.argv[1:]
                is used

        RETURN VALUE
          None

        REMARKS
          None
        """

        levels = {'RAW': gnatpython.logging_util.RAW,
                  'DEBUG': logging.DEBUG,
                  'INFO': logging.INFO,
                  'ERROR': logging.ERROR,
                  'CRITICAL': logging.CRITICAL}

        (self.options, self.args) = self.__option_parser.parse_args(args)

        if not self.__log_handlers_set:
            # First set level of verbosity
            if self.options.verbose:
                level = gnatpython.logging_util.RAW
            else:
                level = levels.get(self.options.loglevel, logging.INFO)

            # Set logging handlers
            default_format = '%(levelname)-8s %(message)s'
            handler = gnatpython.logging_util.add_handlers(
                level=level,
                format=default_format)[0]

            if self.formatter is not None:
                default_format = self.formatter

            if self.options.enable_color:
                handler.setFormatter(ConsoleColorFormatter(default_format))
            else:
                if self.formatter is not None:
                    handler.setFormatter(logging.Formatter(self.formatter))

            # Log to a file if necessary
            if self.options.logfile != "":
                handler = gnatpython.logging_util.add_handlers(
                    level=gnatpython.logging_util.RAW,
                    format='%(asctime)s: %(name)-24s: ' \
                    '%(levelname)-8s %(message)s',
                    filename=self.options.logfile)

            self.__log_handlers_set = True

        # Export options to env
        e = Env()
        e.main_options = self.options

        if self.add_targets_options:
            # Handle --target and --host options
            host_name = None
            host_version = None
            target_name = None
            target_version = None
            target_machine = None

            if self.options.host != "":
                tmp = self.options.host.split(',')
                host_name = tmp[0]
                if len(tmp) > 1:
                    host_version = tmp[1]

            if self.options.target != "":
                tmp = self.options.target.split(',')
                target_name = tmp[0]
                if len(tmp) > 1:
                    target_version = tmp[1]
                if len(tmp) > 2:
                    target_machine = tmp[2]

            e.set_host(host_name, host_version)
            e.set_target(target_name, target_version, target_machine)

    def error(self, msg):
        """Print a usage message incorporating 'msg' to stderr and exit.

        PARAMETERS
        msg: Error message to display
        """
        self.__option_parser.error(msg)

    def create_option_group(self, txt):
        """Create a new option group

        You need to call add_option_group after having added the options
        """
        return OptionGroup(self.__option_parser, txt)

    def add_option_group(self, group):
        """Add groups to parsers"""
        self.__option_parser.add_option_group(group)