~ubuntu-branches/ubuntu/wily/bandit/wily-proposed

« back to all changes in this revision

Viewing changes to bandit/core/config.py

  • Committer: Package Import Robot
  • Author(s): Dave Walker (Daviey)
  • Date: 2015-07-22 09:01:39 UTC
  • Revision ID: package-import@ubuntu.com-20150722090139-fl0nluy0x8m9ctx4
Tags: upstream-0.12.0
ImportĀ upstreamĀ versionĀ 0.12.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding:utf-8 -*-
 
2
#
 
3
# Copyright 2014 Hewlett-Packard Development Company, L.P.
 
4
#
 
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may
 
6
# not use this file except in compliance with the License. You may obtain
 
7
# a copy of the License at
 
8
#
 
9
#      http://www.apache.org/licenses/LICENSE-2.0
 
10
#
 
11
# Unless required by applicable law or agreed to in writing, software
 
12
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 
13
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 
14
# License for the specific language governing permissions and limitations
 
15
# under the License.
 
16
 
 
17
import sys
 
18
 
 
19
import yaml
 
20
 
 
21
from bandit.core import constants
 
22
 
 
23
 
 
24
class BanditConfig():
 
25
 
 
26
    _config = dict()
 
27
    _logger = None
 
28
    _settings = dict()
 
29
 
 
30
    def __init__(self, logger, config_file):
 
31
        '''Attempt to initialize a config dictionary from a yaml file.
 
32
 
 
33
        Error out if loading the yaml file fails for any reason.
 
34
        :param logger: Logger to be used in the case of errors
 
35
        :param config_file: The Bandit yaml config file
 
36
        :return: -
 
37
        '''
 
38
 
 
39
        self._logger = logger
 
40
 
 
41
        try:
 
42
            f = open(config_file, 'r')
 
43
        except IOError:
 
44
            logger.error("could not open config file: %s", config_file)
 
45
            sys.exit(2)
 
46
        else:
 
47
            try:
 
48
                self._config = yaml.safe_load(f)
 
49
            except yaml.YAMLError:
 
50
                logger.error("Invalid config file specified: %s", config_file)
 
51
                sys.exit(2)
 
52
 
 
53
        self._init_settings()
 
54
 
 
55
    def get_option(self, option_string):
 
56
        '''Returns the option from the config specified by the option_string.
 
57
 
 
58
        '.' can be used to denote levels, for example to retrieve the options
 
59
        from the 'a' profile you can use 'profiles.a'
 
60
        :param option_string: The string specifying the option to retrieve
 
61
        :return: The object specified by the option_string, or None if it can't
 
62
        be found.
 
63
        '''
 
64
        option_levels = option_string.split('.')
 
65
        cur_item = self._config
 
66
        for level in option_levels:
 
67
            if level in cur_item:
 
68
                try:
 
69
                    cur_item = cur_item[level]
 
70
                except Exception:
 
71
                    self._logger.error(
 
72
                        "error while accessing config property: %s",
 
73
                        option_string
 
74
                    )
 
75
                    return None
 
76
            else:
 
77
                return None
 
78
 
 
79
        return cur_item
 
80
 
 
81
    def get_setting(self, setting_name):
 
82
        if setting_name in self._settings:
 
83
            return self._settings[setting_name]
 
84
        else:
 
85
            return None
 
86
 
 
87
    @property
 
88
    def config(self):
 
89
        '''Property to return the config dictionary
 
90
 
 
91
        :return: Config dictionary
 
92
        '''
 
93
        return self._config
 
94
 
 
95
    def _init_settings(self):
 
96
        '''This function calls a set of other functions (one per setting)
 
97
 
 
98
        This function calls a set of other functions (one per setting) to build
 
99
        out the _settings dictionary.  Each other function will set values from
 
100
        the config (if set), otherwise use defaults (from constants if
 
101
        possible).
 
102
        :return: -
 
103
        '''
 
104
        self._init_progress_increment()
 
105
        self._init_output_colors()
 
106
        self._init_plugins_dir()
 
107
        self._init_plugin_name_pattern()
 
108
 
 
109
    def _init_progress_increment(self):
 
110
        '''Sets settings['progress'] from default or config file.'''
 
111
        progress = constants.progress_increment
 
112
        if self.get_option('show_progress_every'):
 
113
            progress = self.get_option('show_progress_every')
 
114
        self._settings['progress'] = progress
 
115
 
 
116
    def _init_output_colors(self):
 
117
        '''Sets the settings colors
 
118
 
 
119
        sets settings['color_xxx'] where xxx is DEFAULT, HEADER, LOW, MEDIUM,
 
120
        HIGH
 
121
        '''
 
122
        colors = ['HEADER', 'DEFAULT', 'LOW', 'MEDIUM', 'HIGH']
 
123
        color_settings = dict()
 
124
 
 
125
        isatty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
 
126
 
 
127
        for color in colors:
 
128
            # if not a TTY, overwrite color codes in configuration
 
129
            if not isatty:
 
130
                color_settings[color] = ""
 
131
            # else read color codes in from the config
 
132
            else:
 
133
                # grab the default color from constant
 
134
                color_settings[color] = constants.color[color]
 
135
 
 
136
                # check if the option has been set in config file
 
137
                options_string = 'output_colors.' + color
 
138
                if self.get_option(options_string):
 
139
                    color_string = self.get_option(options_string)
 
140
                    # some manipulation is needed because escape string doesn't
 
141
                    # come back from yaml correctly
 
142
                    if color_string.find('['):
 
143
                        right_half = color_string[color_string.find('['):]
 
144
                        left_half = '\033'
 
145
                        color_settings[color] = left_half + right_half
 
146
 
 
147
            # update the settings dict with the color value
 
148
            settings_string = 'color_' + color
 
149
            self._settings[settings_string] = color_settings[color]
 
150
 
 
151
    def _init_plugins_dir(self):
 
152
        '''Sets settings['plugins_dir'] from default or config file.'''
 
153
        plugins_dir = constants.plugins_dir
 
154
        if self.get_option('plugins_dir'):
 
155
            plugins_dir = self.get_option('plugins_dir')
 
156
        self._settings['plugins_dir'] = plugins_dir
 
157
 
 
158
    def _init_plugin_name_pattern(self):
 
159
        '''Sets settings['plugin_name_pattern'] from default or config file.'''
 
160
        plugin_name_pattern = constants.plugin_name_pattern
 
161
        if self.get_option('plugin_name_pattern'):
 
162
            plugin_name_pattern = self.get_option('plugin_name_pattern')
 
163
        self._settings['plugin_name_pattern'] = plugin_name_pattern