1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0+ 3 4from os import path 5import os, csv 6from itertools import chain 7 8from csv_collection import CSVCollection 9from ni_names import value_to_name 10import ni_values 11 12CSV_DIR = 'csv' 13 14def iter_src_values(D): 15 return D.items() 16 17def iter_src(D): 18 for dest in D: 19 yield dest, 1 20 21def create_csv(name, D, src_iter): 22 # have to change dest->{src:val} to src->{dest:val} 23 fieldnames = [value_to_name[i] for i in sorted(D.keys())] 24 fieldnames.insert(0, CSVCollection.source_column_name) 25 26 S = dict() 27 for dest, srcD in D.items(): 28 for src,val in src_iter(srcD): 29 S.setdefault(src,{})[dest] = val 30 31 S = sorted(S.items(), key = lambda src_destD : src_destD[0]) 32 33 34 csv_fname = path.join(CSV_DIR, name + '.csv') 35 with open(csv_fname, 'w') as F_csv: 36 dR = csv.DictWriter(F_csv, fieldnames, delimiter=';', quotechar='"') 37 dR.writeheader() 38 39 # now change the json back into the csv dictionaries 40 rows = [ 41 dict(chain( 42 ((CSVCollection.source_column_name,value_to_name[src]),), 43 *(((value_to_name[dest],v),) for dest,v in destD.items()) 44 )) 45 for src, destD in S 46 ] 47 48 dR.writerows(rows) 49 50 51def to_csv(): 52 for d in ['route_values', 'device_routes']: 53 try: 54 os.makedirs(path.join(CSV_DIR,d)) 55 except: 56 pass 57 58 for family, dst_src_map in ni_values.ni_route_values.items(): 59 create_csv(path.join('route_values',family), dst_src_map, iter_src_values) 60 61 for device, dst_src_map in ni_values.ni_device_routes.items(): 62 create_csv(path.join('device_routes',device), dst_src_map, iter_src) 63 64 65if __name__ == '__main__': 66 to_csv() 67