#!/usr/bin/env python3 import typing def get_return_type(levels: int, dtype: str) -> str: return ("map[string]" * levels) + dtype def get_signature(levels: int, sig_dtype: str, dtype: str) -> str: return ( "func (c *Config) get" + ("Map" * levels) + sig_dtype + "(key string) (empty " + get_return_type(levels, dtype) + ") {" ) def get_empty_def(levels: int, dtype: str) -> str: return "empty = make(" + get_return_type(levels, dtype) + ")" def get_nested_keys(levels: int) -> str: txt = "" for count in range(levels): txt += "[k" + str(count + 10) + "]" return txt def get_retval_def(levels: int, current_level: int, dtype: str) -> str: base = "retval := make(" if current_level > 0: base = "retval" + get_nested_keys(current_level) + " = make(" return base + get_return_type(levels - current_level, dtype) + ")" def get_entries(levels: int) -> str: return f"v9, ok := c.mapEnv[{levels}].next[key]" def get_entry(levels: int) -> str: return f"entry := c.env[v{levels}.key]" def get_loop(levels: int) -> str: return f"for k{levels + 10}, v{levels + 10} := range v{levels + 9}.next {{" def get_function(file: typing.TextIO, levels: int, sig_dtype: str, dtype: str): print(get_signature(levels, sig_dtype, dtype), file=file) print(get_empty_def(levels, dtype), file=file) print(get_retval_def(levels, 0, dtype), file=file) print("if c.parsed {", file=file) print("key = cleanKey(key)", file=file) print(get_entries(levels), file=file) for level in range(levels): print(get_loop(level), file=file) print(get_retval_def(levels, level, dtype), file=file) print(get_loop(levels), file=file) print(get_entry(levels), file=file) print( "if (entry.dtype.baseType() == dtype.baseType()) && (entry.parsed.err == nil) {", file=file, ) print("retval[k] = entry.parsed", file=file) print("} else {", file=file) print("return", file=file) print("}", file=file) print("}", file=file) print("return retval", file=file) print("}", file=file) print("}", file=file) print("return", file=file) print("}", file=file) with open("generated_code.go", mode="w", encoding="utf-8") as f: print("package envconf", file=f) get_function(f, 3, "Int", "int64") # # func (c *Config) getRawMap(key string, dtype DataType) (empty map[string]cValue) { # empty = make(map[string]cValue) # retval := make(map[string]cValue) # if c.parsed { # key = cleanKey(key) # entries, ok := c.mapEnv[0].next[key] # # if ok { # for k, v := range entries.next { # entry := c.env[v.key] # if (entry.dtype.baseType() == dtype.baseType()) && (entry.parsed.err == nil) { # retval[k] = entry.parsed # } else { # return # } # } # return retval # } # } # return # } # #