File: merge-features.py

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (84 lines) | stat: -rwxr-xr-x 2,223 bytes parent folder | download
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
#!/usr/bin/env python3

import argparse
import json
import sys


def error(message):
    sys.stderr.write(message)
    sys.stderr.write("\n")
    sys.exit(1)


def invalid_file(features_file, message):
    error(f"Invalid features file '{features_file}': {message}")


def parse_args():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="""
        Merges the given feature files together into stdout. Each file FILE
        must be given a corresponding PREFIX to prefix the name of each entry
        in its features list, though these could be empty if no prefix is
        required.

        Note that the files and prefixes are treated as an ordered list, ie.
        the first FILE corresponds to the first PREFIX.
        """)

    parser.add_argument(
        "--file", "-f", action="append", dest="files",
        help="path of a file to merge"
    )
    parser.add_argument(
        "--prefix", "-p", action="append", dest="prefixes",
        help="prefix to prepend to the name of each feature"
    )

    return parser.parse_known_args()


def read_features(from_file, add_prefix):
    with open(from_file, "r") as f:
        features_dict = json.load(f)

    if "features" not in features_dict:
        invalid_file(from_file, "missing 'features' key")

    features = []
    for feature in features_dict["features"]:
        if "name" not in feature:
            invalid_file(from_file, "missing name in features list")

        new_feature = {"name": add_prefix + feature["name"]}

        if "value" in feature:
            new_feature.update({"value" : feature["value"]})

        features.append(new_feature)
    return features


def main():
    (args, _) = parse_args()

    if not args.files:
        error("No files to merge were provided")

    if len(args.files) != len(args.prefixes):
        error("Must supply the same number of files and prefixes")

    features = []
    for i, (f, prefix) in enumerate(zip(args.files, args.prefixes)):
        features.extend(read_features(f, prefix))

    data = {
        "features": features
    }
    sys.stdout.write(json.dumps(data, indent=2))


if __name__ == '__main__':
    main()