Convert yang2props.py to python 3
[sdnc/northbound.git] / generic-resource-api / model / scripts / python / yang2props.py
1 #!/usr/bin/python
2
3 import re
4 import sys
5
6
7 # Convert word from foo-bar to FooBar
8 # words begining with a digit will be converted to _digit
9 def to_enum(s):
10     if s[0].isdigit():
11         s = "_" + s
12     else:
13         s = s[0].upper() + s[1:]
14     return re.sub(r'(?!^)-([a-zA-Z])', lambda m: m.group(1).upper(), s)
15
16 leaf = ""
17 val = ""
18 li = []
19
20 if len(sys.argv) < 3:
21      print('yang2props.py <input yang> <output properties>')
22      sys.exit(2)
23
24 with open(sys.argv[1], "r") as ins:
25     for line in ins:
26         # if we see a leaf save the name for later
27         if "leaf " in line:
28             match = re.search(r'leaf (\S+)', line)
29             if match:
30                 leaf = match.group(1)
31       
32         # if we see enum convert the value to enum format and see if it changed
33         # if the value is different write a property entry
34         if "enum " in line:
35             match = re.search(r'enum "(\S+)";', line)
36             if match:
37                 val = match.group(1)
38                 enum = to_enum(val)
39
40                 # see if converting to enum changed the string
41                 if val != enum:
42                     property = "yang."+leaf+"."+enum+"="+val
43                     if property not in li:
44                         li.append( property)
45
46
47 # Open output file
48 fo = open(sys.argv[2], "w")
49 fo.write("# yang conversion properties \n")
50 fo.write("# used to convert Enum back to the original yang value \n")
51 fo.write("\n".join(li))
52 fo.write("\n")
53
54 # Close opend file
55 fo.close()
56
57