def __getitem__(self, value): return self.value_map[value] def get_name(self, value, name): try: return self[value] except KeyError: i = self.c[name] return self.new_name(name, i) def new_name(self, name, i): if i == 0: return name else: return "{}Dup{}".format(name, i) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--package", type=str, default="autogen") parser.add_argument("--name", type=str, default="AutoGenerated") parser.add_argument("src", type=argparse.FileType('r')) args = parser.parse_args() m = GoModule() m.package(args.package) print(json_to_go(args.src.read(), args.name, m))
def _emit_struct(self, state, name, m, parent=None): with m.block("{} struct".format(name)): for name, substate in sorted(state["children"].items()): self._emit(substate, name, m, parent=state) jsonname = self.value_formatter.to_jsonname(state) if self.value_formatter.is_omitempty(state, parent): m.insert_after(' `json:"{},omitempty"`'.format(jsonname)) else: m.insert_after(' `json:"{}"`'.format(jsonname)) def _emit_field(self, state, name, m, parent=None): typ = self.value_formatter.to_type(state) jsonname = self.value_formatter.to_jsonname(state) if self.value_formatter.is_omitempty(state, parent): m.stmt('{} {} `json:"{},omitempty"`'.format(name, typ, jsonname)) else: m.stmt('{} {} `json:"{}"`'.format(name, typ, jsonname)) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--package", type=str, default="autogen") parser.add_argument("--name", type=str, default="AutoGenerated") parser.add_argument("src", type=argparse.FileType('r')) args = parser.parse_args() m = GoModule() m.package(args.package) print(json_to_go(args.src.read(), args.name, m))
# -*- coding:utf-8 -*- from prestring.go import GoModule # cross product def crossN(m, n): def rec(m, i, value): if i >= n: m.stmt("r = append(r, []string{{{value}}})".format(value=", ".join(value))) else: v = "v{}".format(i) vs = "vs{}".format(i) with m.for_("_, {} := range {}".format(v, vs)): value.append(v) rec(m, i + 1, value) args = ["vs{} []string".format(i) for i in range(n)] with m.func("cross{}".format(n), *args, return_="[][]string"): m.stmt("var r [][]string") rec(m, 0, []) m.return_("r") return m m = GoModule() m.package("main") print(crossN(m, 5))
# -*- coding:utf-8 -*- from prestring.go import GoModule # cross product def cross2(m): with m.func("cross2", "vs0 []string", "vs1 []string", return_="[][]string"): m.stmt("var r [][]string") with m.for_("_, v0 := range vs0"): with m.for_("_, v1 := range vs1"): m.stmt("r = append(r, []string{v0, v1})") m.return_("r") return m m = GoModule() m.package("main") print(cross2(m))
def main(): parser = argparse.ArgumentParser() parser.add_argument("--src", required=True) parser.add_argument("--dst", required=True) args = parser.parse_args() reader = Reader() with open(args.src) as rf: src_world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict)) src_world.normalize() with open(args.dst) as rf: dst_world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict)) dst_world.normalize() gencoder = MiniCodeGenerator(TypeMappingResolver([])) m = GoModule() m.package("convert") with m.import_group() as im: iw = ImportWriter(im) convertor = TypeConvertor(iw, gencoder, src_world, dst_world) iw.import_(src_world["model"]) iw.import_(dst_world["def"]) @convertor.as_override("string", src_world["bson"].fulladdress("ObjectId")) def string_to_object_id(convertor, m, value, *args): new_prefix = convertor.import_writer.import_(src_world["bson"]) return "{}.ObjectIdHex({})".format(new_prefix, value) @convertor.as_override(src_world["bson"].fulladdress("ObjectId"), "string") def object_id_to_string(convertor, m, value, *args): return "{}.Hex()".format(value) @convertor.as_override(src_world["model"].fulladdress("Date"), "time.Time") def model_date_to_time(convertor, m, value, *args): return "{}.Time()".format(value) @convertor.as_override(src_world["bson"].fulladdress("ObjectId"), ("pointer", dst_world["def"].fulladdress("ID"))) def object_id_to_id(convertor, m, value, *args): return "ConvertID({})".format(value) m.sep() cw = ConvertWriter(m, convertor) for module in dst_world.modules.values(): for file in module.files.values(): for struct in file.structs.values(): for module in src_world.modules.values(): if struct.name in module: print("@", struct.name, file=sys.stderr) cw.write_function(module[struct.name], struct) elif struct.name.startswith("Enduser") and struct.name[len("Enduser"):] in module: print("<", struct.name, file=sys.stderr) cw.write_function(module[struct.name[len("Enduser"):]], struct) elif struct.name.startswith("Tuner") and struct.name[len("Tuner"):] in module: print(">", struct.name, file=sys.stderr) cw.write_function(module[struct.name[len("Tuner"):]], struct) # cw.write_function(src_world["model"]["Page"], dst_world["def"]["Page"]) # # cw.write_function(dst_world["def"]["Page"], src_world["model"]["Page"]) # cw.write_function(src_world["model"]["User"], dst_world["def"]["User"]) print(m)