This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
generator.py
92 lines (73 loc) · 2.86 KB
/
generator.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
85
86
87
88
89
90
91
92
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Self Service Printer Installer generator script
Assembles all the source files into a usable script
"""
import csv
import json
import argparse
def build_argparser():
"""Creates the argument parser"""
parser = argparse.ArgumentParser(
description=("Takes an input CSV of printer queues and converts the "
"list to a JSON document, then injects the JSON into "
"the Python template.")
)
parser.add_argument("config",
type=argparse.FileType("r"),
help="Path to JSON configuration file")
parser.add_argument("infile",
type=argparse.FileType("r"),
help="Path to input CSV file of printer queues")
parser.add_argument("exclude",
nargs="?",
type=argparse.FileType("r"),
help="Path to optional exclusions file")
args = parser.parse_args()
return args.config, args.infile, args.exclude
def main():
"""Main program"""
# Grab the passed arguments
config, infile, exclude = build_argparser()
# Load the config
cfg = json.loads(config.read())
# Open file handles for needed i/o files
output_json_file = open(cfg["generator"]["output_json_file"], 'w+')
input_python_template = open(cfg["generator"]["input_python_template"], 'r')
output_script = open(cfg["generator"]["output_script"], 'w+')
# Split the exclusions, if they exist
exclusions = []
if exclude:
exclusions = exclude.read().splitlines()
# Process the CSV into a dictionary
csv_data = csv.DictReader(infile)
# Ensure required fields are present
required_fields = ['DisplayName', 'URI', 'Driver', 'DriverTrigger',
'Location']
present_fields = csv_data.fieldnames
for required_field in required_fields:
if required_field not in present_fields:
print "Missing required CSV field: " + required_field
quit()
# Convert each row into a dictionary
lines = {}
for line in csv_data:
if line['DisplayName'] not in exclusions:
if line['Options']:
opts = dict(item.split('=') for item in line['Options'].split(' '))
line['Options'] = opts
lines[line['DisplayName']] = line
# Format the dictionary as JSON
json_data = json.dumps(lines, sort_keys=False, indent=4,
separators=(',', ': '))
# Write the JSON to file
output_json_file.write(json_data)
output_json_file.close()
# Inject the JSON into the Python template
template = input_python_template.read()
output_script.write(template.format(queues=json_data, config=cfg))
output_script.close()
print "Done."
if __name__ == '__main__':
main()