File: gen_feature_definitions.py

package info (click to toggle)
firefox-esr 128.13.0esr-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,230,012 kB
  • sloc: cpp: 7,103,971; javascript: 6,088,450; ansic: 3,653,980; python: 1,212,330; xml: 594,604; asm: 420,652; java: 182,969; sh: 71,124; makefile: 20,747; perl: 13,449; objc: 12,399; yacc: 4,583; cs: 3,846; pascal: 2,973; lex: 1,720; ruby: 1,194; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10
file content (164 lines) | stat: -rwxr-xr-x 5,063 bytes parent folder | download | duplicates (6)
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
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

import json
import re
import sys
import toml
import voluptuous
import voluptuous.humanize
from voluptuous import Schema, Optional, Any, All, Required, Length, Range, Msg, Match


Text = Any(str, bytes)


id_regex = re.compile(r"^[a-z0-9-]+$")
feature_schema = Schema(
    {
        Match(id_regex): {
            Required("title"): All(Text, Length(min=1)),
            Required("description"): All(Text, Length(min=1)),
            Required("bug-numbers"): All(Length(min=1), [All(int, Range(min=1))]),
            Required("restart-required"): bool,
            Required("type"): "boolean",  # In the future this may include other types
            Optional("preference"): Text,
            Optional("default-value-jexl"): Text,
            Optional("is-public-jexl"): Text,
            Optional("description-links"): dict,
        },
    }
)


EXIT_OK = 0
EXIT_ERROR = 1


def main(output, *filenames):
    features = {}
    errors = False
    try:
        features = process_files(filenames)
        json.dump(features, output, sort_keys=True)
    except ExceptionGroup as error_group:
        print(str(error_group))
        return EXIT_ERROR
    return EXIT_OK


class ExceptionGroup(Exception):
    def __init__(self, errors):
        self.errors = errors

    def __str__(self):
        rv = ["There were errors while processing feature definitions:"]
        for error in self.errors:
            # indent the message
            s = "\n".join("    " + line for line in str(error).split("\n"))
            # add a * at the beginning of the first line
            s = "  * " + s[4:]
            rv.append(s)
        return "\n".join(rv)


class FeatureGateException(Exception):
    def __init__(self, message, filename=None):
        super(FeatureGateException, self).__init__(message)
        self.filename = filename

    def __str__(self):
        message = super(FeatureGateException, self).__str__()
        rv = ["In"]
        if self.filename is None:
            rv.append("unknown file:")
        else:
            rv.append('file "{}":\n'.format(self.filename))
        rv.append(message)
        return " ".join(rv)

    def __repr__(self):
        # Turn "FeatureGateExcept(<message>,)" into "FeatureGateException(<message>, filename=<filename>)"
        original = super(FeatureGateException, self).__repr__()
        with_comma = original[:-1]
        # python 2 adds a trailing comma and python 3 does not, so we need to conditionally reinclude it
        if len(with_comma) > 0 and with_comma[-1] != ",":
            with_comma = with_comma + ","
        return with_comma + " filename={!r})".format(self.filename)


def process_files(filenames):
    features = {}
    errors = []

    for filename in filenames:
        try:
            with open(filename, "r") as f:
                feature_data = toml.load(f)

            voluptuous.humanize.validate_with_humanized_errors(
                feature_data, feature_schema
            )

            for feature_id, feature in feature_data.items():
                feature["id"] = feature_id
                features[feature_id] = expand_feature(feature)
        except (
            voluptuous.error.Error,
            IOError,
            FeatureGateException,
            toml.TomlDecodeError,
        ) as e:
            # Wrap errors in enough information to know which file they came from
            errors.append(FeatureGateException(e, filename))

    if errors:
        raise ExceptionGroup(errors)

    return features


def hyphens_to_camel_case(s):
    """Convert names-with-hyphens to namesInCamelCase"""
    rv = ""
    for part in s.split("-"):
        if rv == "":
            rv = part.lower()
        else:
            rv += part[0].upper() + part[1:].lower()
    return rv


def expand_feature(feature):
    """Fill in default values for optional fields"""

    # convert all names-with-hyphens to namesInCamelCase
    key_changes = []
    for key in feature.keys():
        if "-" in key:
            new_key = hyphens_to_camel_case(key)
            key_changes.append((key, new_key))

    for old_key, new_key in key_changes:
        feature[new_key] = feature[old_key]
        del feature[old_key]

    if feature["type"] == "boolean":
        feature.setdefault("preference", "features.{}.enabled".format(feature["id"]))
        # set default value to None so that we can test for preferences where we forgot to set the default value
        feature.setdefault("defaultValueJexl", None)
    elif "preference" not in feature:
        raise FeatureGateException(
            "Features of type {} must specify an explicit preference name".format(
                feature["type"]
            )
        )

    feature.setdefault("isPublicJexl", "false")
    return feature


if __name__ == "__main__":
    sys.exit(main(sys.stdout, *sys.argv[1:]))