- Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathmerge-features.py
executable file
·84 lines (59 loc) · 2.17 KB
/
merge-features.py
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
importargparse
importjson
importsys
deferror(message):
sys.stderr.write(message)
sys.stderr.write("\n")
sys.exit(1)
definvalid_file(features_file, message):
error(f"Invalid features file '{features_file}': {message}")
defparse_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"
)
returnparser.parse_known_args()
defread_features(from_file, add_prefix):
withopen(from_file, "r") asf:
features_dict=json.load(f)
if"features"notinfeatures_dict:
invalid_file(from_file, "missing 'features' key")
features= []
forfeatureinfeatures_dict["features"]:
if"name"notinfeature:
invalid_file(from_file, "missing name in features list")
new_feature= {"name": add_prefix+feature["name"]}
if"value"infeature:
new_feature.update({"value" : feature["value"]})
features.append(new_feature)
returnfeatures
defmain():
(args, _) =parse_args()
ifnotargs.files:
error("No files to merge were provided")
iflen(args.files) !=len(args.prefixes):
error("Must supply the same number of files and prefixes")
features= []
fori, (f, prefix) inenumerate(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()