summaryrefslogtreecommitdiffstats
path: root/gitlint/config.py
blob: 602ff002e2dacc7f67ad80e92b02c3012debc35b (plain)
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
try:
    # python 2.x
    from ConfigParser import ConfigParser, Error as ConfigParserError
except ImportError:  # pragma: no cover
    # python 3.x
    from configparser import ConfigParser, Error as ConfigParserError  # pragma: no cover, pylint: disable=import-error

import re
import os
import shutil

try:
    # python >= 2.7
    from collections import OrderedDict
except ImportError:  # pragma: no cover
    # python 2.4-2.6
    from ordereddict import OrderedDict  # pragma: no cover

from gitlint import rules
from gitlint import options


class LintConfigError(Exception):
    pass


class LintConfig(object):
    """ Class representing gitlint configuration.
        Contains active config as well as number of methods to easily get/set the config
        (such as reading it from file or parsing commandline input).
    """
    default_rule_classes = [rules.TitleMaxLength,
                            rules.TitleTrailingWhitespace,
                            rules.TitleLeadingWhitespace,
                            rules.TitleTrailingPunctuation,
                            rules.TitleHardTab,
                            rules.TitleMustNotContainWord,
                            rules.TitleRegexMatches,
                            rules.BodyMaxLineLength,
                            rules.BodyMinLength,
                            rules.BodyMissing,
                            rules.BodyTrailingWhitespace,
                            rules.BodyHardTab,
                            rules.BodyFirstLineEmpty,
                            rules.BodyChangedFileMention]

    def __init__(self, config_path=None, target=None):
        # Use an ordered dict so that the order in which rules are applied is always the same
        self._rules = OrderedDict([(rule_cls.id, rule_cls()) for rule_cls in self.default_rule_classes])
        self._verbosity = options.IntOption('verbosity', 3, "Verbosity")
        self._ignore_merge_commits = options.BoolOption('ignore-merge-commits', True, "Ignore merge commits")
        self.config_path = config_path
        if target:
            self.target = target
        else:
            self.target = os.path.abspath(os.getcwd())

    @property
    def verbosity(self):
        return self._verbosity.value

    @verbosity.setter
    def verbosity(self, value):
        try:
            self._verbosity.set(value)
            if self.verbosity < 0 or self.verbosity > 3:
                raise LintConfigError("Option 'verbosity' must be set between 0 and 3")
        except options.RuleOptionError as e:
            raise LintConfigError(str(e))

    @property
    def ignore_merge_commits(self):
        return self._ignore_merge_commits.value

    @ignore_merge_commits.setter
    def ignore_merge_commits(self, value):
        try:
            return self._ignore_merge_commits.set(value)
        except options.RuleOptionError as e:
            raise LintConfigError(str(e))

    @property
    def rules(self):
        return [rule for rule in self._rules.values()]

    @property
    def body_rules(self):
        return [rule for rule in self._rules.values() if isinstance(rule, rules.CommitMessageBodyRule)]

    @property
    def title_rules(self):
        return [rule for rule in self._rules.values() if isinstance(rule, rules.CommitMessageTitleRule)]

    def disable_rule_by_id(self, rule_id):
        del self._rules[rule_id]

    def disable_rule(self, rule_id_or_name):
        if rule_id_or_name == "all":
            self._rules = OrderedDict()
        else:
            rule = self.get_rule(rule_id_or_name)
            if rule:
                self.disable_rule_by_id(rule.id)

    def get_rule(self, rule_id_or_name):
        # try finding rule by id
        rule = self._rules.get(rule_id_or_name)
        # if not found, try finding rule by name
        if not rule:
            rule = next((rule for rule in self._rules.values() if rule.name == rule_id_or_name), None)
        return rule

    def _get_option(self, rule_name_or_id, option_name):
        rule = self.get_rule(rule_name_or_id)
        if not rule:
            raise LintConfigError("No such rule '{0}'".format(rule_name_or_id))

        option = rule.options.get(option_name)
        if not option:
            raise LintConfigError("Rule '{0}' has no option '{1}'".format(rule_name_or_id, option_name))

        return option

    def get_rule_option(self, rule_name_or_id, option_name):
        """ Returns the value of a given option for a given rule. LintConfigErrors will be raised if the
        rule or option don't exist. """
        option = self._get_option(rule_name_or_id, option_name)
        return option.value

    def set_rule_option(self, rule_name_or_id, option_name, option_value):
        """ Attempts to set a given value for a given option for a given rule.
            LintConfigErrors will be raised if the rule or option don't exist or if the value is invalid. """
        option = self._get_option(rule_name_or_id, option_name)
        try:
            option.set(option_value)
        except options.RuleOptionError as e:
            raise LintConfigError(
                "'{0}' is not a valid value for option '{1}.{2}'. {3}.".format(option_value, rule_name_or_id,
                                                                               option_name, str(e)))

    def apply_config_from_commit(self, commit):
        """ Given a git commit, applies config specified in the commit message.
            Supported:
             - gitlint-ignore: all
        """
        for line in commit.message.full.split("\n"):
            pattern = re.compile(r"^gitlint-ignore:\s*(.*)")
            matches = pattern.match(line)
            if matches and len(matches.groups()) == 1:
                self.set_general_option('ignore', matches.group(1))

    def apply_config_options(self, config_options):
        """ Given a list of config options of the form "<rule>.<option>=<value>", parses out the correct rule and option
        and sets the value accordingly in this config object. """
        for config_option in config_options:
            try:
                config_name, option_value = config_option.split("=", 1)
                if not option_value:
                    raise ValueError()
                rule_name, option_name = config_name.split(".", 1)
                if rule_name == "general":
                    self.set_general_option(option_name, option_value)
                else:
                    self.set_rule_option(rule_name, option_name, option_value)
            except ValueError:  # raised if the config string is invalid
                raise LintConfigError(
                    "'{0}' is an invalid configuration option. Use '<rule>.<option>=<value>'".format(config_option))

    def set_general_option(self, option_name, option_value):
        if option_name == "ignore":
            self.apply_on_csv_string(option_value, self.disable_rule)
        elif option_name == "verbosity":
            self.verbosity = int(option_value)
        elif option_name == "ignore-merge-commits":
            self.ignore_merge_commits = option_value
        else:
            raise LintConfigError("'{0}' is not a valid gitlint option".format(option_name))

    @staticmethod
    def apply_on_csv_string(rules_str, func):
        """ Splits a given string by comma, trims whitespace on the resulting strings and applies a given ```func``` to
        each item. """
        splitted = rules_str.split(",")
        for str in splitted:
            func(str.strip())

    @staticmethod
    def load_from_file(filename):
        """ Loads lint config from a ini-style config file """
        if not os.path.exists(filename):
            raise LintConfigError("Invalid file path: {0}".format(filename))
        config = LintConfig(config_path=os.path.abspath(filename))
        try:
            parser = ConfigParser()
            parser.read(filename)
            LintConfig._parse_general_section(parser, config)
            LintConfig._parse_rule_sections(parser, config)
        except ConfigParserError as e:
            raise LintConfigError(str(e))

        return config

    @staticmethod
    def _parse_rule_sections(parser, config):
        sections = [section for section in parser.sections() if section != "general"]
        for rule_name in sections:
            for option_name, option_value in parser.items(rule_name):
                config.set_rule_option(rule_name, option_name, option_value)

    @staticmethod
    def _parse_general_section(parser, config):
        if parser.has_section('general'):
            for option_name, option_value in parser.items('general'):
                config.set_general_option(option_name, option_value)

    def __eq__(self, other):
        return self.rules == other.rules and \
               self.verbosity == other.verbosity and \
               self.target == other.target and \
               self.config_path == other.config_path  # noqa


GITLINT_CONFIG_TEMPLATE_SRC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "files/gitlint")


class LintConfigGenerator(object):
    @staticmethod
    def generate_config(dest):
        """ Generates a gitlint config file at the given destination location.
            Expects that the given ```dest``` points to a valid destination. """
        shutil.copyfile(GITLINT_CONFIG_TEMPLATE_SRC_PATH, dest)