|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import sys |
| 6 | + |
| 7 | + |
| 8 | +def error(message): |
| 9 | + sys.stderr.write(message) |
| 10 | + sys.stderr.write("\n") |
| 11 | + sys.exit(1) |
| 12 | + |
| 13 | + |
| 14 | +def invalid_file(features_file, message): |
| 15 | + error(f"Invalid features file '{features_file}': {message}") |
| 16 | + |
| 17 | + |
| 18 | +def parse_args(): |
| 19 | + parser = argparse.ArgumentParser( |
| 20 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 21 | + description=""" |
| 22 | + Merges the given feature files together into DEST (or stdout if DEST |
| 23 | + is not given). Each file FILE must be given a corresponding PREFIX to |
| 24 | + prefix the name of each entry in its features list, though these could |
| 25 | + be empty if no prefix is required. |
| 26 | +
|
| 27 | + Note that the files and prefixes are treated as an ordered list, ie. |
| 28 | + the first FILE corresponds to the first PREFIX. |
| 29 | + """) |
| 30 | + |
| 31 | + parser.add_argument( |
| 32 | + "--file", "-f", action="append", dest="files", |
| 33 | + help="path of a file to merge" |
| 34 | + ) |
| 35 | + parser.add_argument( |
| 36 | + "--prefix", "-p", action="append", dest="prefixes", |
| 37 | + help="prefix to prepend to the name of each feature" |
| 38 | + ) |
| 39 | + parser.add_argument( |
| 40 | + "dest", nargs="?", |
| 41 | + help="path to store the merged file" |
| 42 | + ) |
| 43 | + |
| 44 | + return parser.parse_known_args() |
| 45 | + |
| 46 | + |
| 47 | +def read_features(from_file, add_prefix): |
| 48 | + with open(from_file, "r") as f: |
| 49 | + features_dict = json.load(f) |
| 50 | + |
| 51 | + if "features" not in features_dict: |
| 52 | + invalid_file(from_file, "missing 'features' key") |
| 53 | + |
| 54 | + features = [] |
| 55 | + for feature in features_dict["features"]: |
| 56 | + if "name" not in feature: |
| 57 | + invalid_file(from_file, "missing name in features list") |
| 58 | + |
| 59 | + features.append({"name": add_prefix + feature["name"]}) |
| 60 | + return features |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + (args, _) = parse_args() |
| 65 | + |
| 66 | + if not args.files: |
| 67 | + error("No files to merge were provided") |
| 68 | + |
| 69 | + if len(args.files) != len(args.prefixes): |
| 70 | + error("Must supply the same number of files and prefixes") |
| 71 | + |
| 72 | + features = [] |
| 73 | + for i, (f, prefix) in enumerate(zip(args.files, args.prefixes)): |
| 74 | + features.extend(read_features(f, prefix)) |
| 75 | + |
| 76 | + data = { |
| 77 | + "features": features |
| 78 | + } |
| 79 | + |
| 80 | + if args.dest: |
| 81 | + with open(args.dest, "w") as f: |
| 82 | + json.dump(data, f, indent=2) |
| 83 | + else: |
| 84 | + sys.stdout.write(json.dumps(data, indent=2)) |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == '__main__': |
| 88 | + main() |
0 commit comments