mirror of
https://github.com/kiteco/kiteco-public.git
synced 2024-09-11 13:38:04 +03:00
87 lines
2.2 KiB
Python
Executable File
87 lines
2.2 KiB
Python
Executable File
#!/usr/bin/env python
|
|
|
|
import sys
|
|
from pprint import pprint
|
|
from subprocess import call
|
|
|
|
SO_PREFIX = "XML"
|
|
|
|
class StackOverflowXMLStruct(object):
|
|
def __init__(self, name):
|
|
self.name = name
|
|
self.proto = name
|
|
self.fields = []
|
|
if self.name.startswith(SO_PREFIX):
|
|
self.proto = self.name[len(SO_PREFIX):]
|
|
|
|
def add_field(self, name, fieldType):
|
|
if fieldType != "xml.Name":
|
|
self.fields.append((name, fieldType))
|
|
|
|
def to_newfunc(self):
|
|
ret = ("// New%s is generated by xmlgen.py, based on "
|
|
"%s in stackoverflow-xml.go\n" % (self.proto, self.name))
|
|
ret += "func New%s(s *%s) *%s {\n" % (
|
|
self.proto, self.name, self.proto)
|
|
ret += "\treturn &%s{\n" % self.proto
|
|
for name, fieldType in self.fields:
|
|
ret += "\t\t%s: proto.%s(s.%s),\n" % (
|
|
name, fieldType.title(), name)
|
|
ret += "\t}\n"
|
|
ret += "}\n\n"
|
|
return ret
|
|
|
|
def to_proto(self):
|
|
count = 1
|
|
ret = "message %s {\n" % self.proto
|
|
for name, fieldType in self.fields:
|
|
ret += " required %s %s = %d;\n" % (
|
|
fieldType.lower(), name, count)
|
|
count += 1
|
|
ret += "};\n\n"
|
|
return ret
|
|
|
|
|
|
IN_STRUCT = 1
|
|
ON_FIELD = 2
|
|
END_STRUCT = 3
|
|
|
|
def main(filename):
|
|
structs = []
|
|
struct = None
|
|
state = None
|
|
for line in open(filename).readlines():
|
|
if line.startswith("type"):
|
|
parts = line.split()
|
|
struct = StackOverflowXMLStruct(parts[1])
|
|
state = ON_FIELD
|
|
continue
|
|
|
|
if line.startswith("}"):
|
|
state = END_STRUCT
|
|
structs.append(struct)
|
|
struct = None
|
|
|
|
if state == ON_FIELD:
|
|
parts = line.split()
|
|
struct.add_field(parts[0], parts[1])
|
|
|
|
gofp = open('xmlgen.go', 'w')
|
|
gofp.write("package stackoverflow\n\n")
|
|
|
|
protofp = open('xmlgen.proto', 'w')
|
|
protofp.write("package stackoverflow;\n\n")
|
|
|
|
for s in structs:
|
|
protofp.write(s.to_proto())
|
|
gofp.write(s.to_newfunc())
|
|
|
|
protofp.close()
|
|
gofp.close()
|
|
|
|
call(["goimports", "-w", "xmlgen.go"])
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv[1])
|
|
|