code / tomo

Lines41.3K C23.7K Markdown9.7K YAML5.0K Tomo2.3K
7 others 763
Python231 Shell230 make212 INI47 Text21 SVG16 Lua6
(80 lines)
1 #!/bin/env python3
3 # This script converts API YAML files into markdown documentation
4 # and prints it to standard out.
6 import yaml
7 import re
9 def arg_signature(name, arg):
10 sig = name
11 if "type" in arg:
12 sig = sig + ": " + arg["type"]
13 if "default" in arg:
14 sig = sig + " = " + arg["default"]
15 return sig
17 def get_signature(name, info):
18 if "type" in info:
19 return name + " : " + info["type"]
20 sig = name + " : func("
21 if info["args"]:
22 sig += ", ".join(arg_signature(name,arg) for name,arg in info["args"].items())
23 sig += " -> " + info["return"].get("type", "Void")
24 else:
25 sig += "-> " + info["return"].get("type", "Void")
26 sig += ")"
27 return sig
29 def print_method(name, info):
30 print(f"## {name}")
31 print(f"\n```tomo\n{get_signature(name, info)}\n```\n")
32 if "description" in info:
33 print(info["description"])
34 if "note" in info:
35 print(info["note"])
36 if "errors" in info:
37 print(info["errors"])
39 if "args" in info and info["args"]:
40 print("Argument | Type | Description | Default")
41 print("---------|------|-------------|---------")
42 for arg,arg_info in info["args"].items():
43 default = '`'+arg_info['default']+'`' if 'default' in arg_info else '-'
44 description = arg_info['description'].replace('\n', ' ')
45 print(f"{arg} | `{arg_info.get('type', '')}` | {description} | {default}")
46 #print(f"- **{arg}:** {arg_info['description']}")
48 if "return" in info:
49 print(f"\n**Return:** {info['return'].get('description', 'Nothing.')}")
51 if "example" in info:
52 print(f"\n**Example:**\n```tomo\n{info['example']}\n```")
54 def convert_to_markdown(yaml_doc:str)->str:
55 data = yaml.safe_load(yaml_doc)
57 print("# Builtins")
58 for name in sorted([k for k in data.keys() if "." not in k]):
59 print_method(name, data[name])
61 section = None
62 for name in sorted([k for k in data.keys() if "." in k]):
63 if section is None or not name.startswith(section + "."):
64 match = re.match(r"(\w+)\.", name)
65 section = match.group(1)
66 print(f"\n# {section}")
68 print_method(name, data[name])
70 if __name__ == "__main__":
71 import sys
72 print("% API\n")
73 if len(sys.argv) > 1:
74 all_files = ""
75 for filename in sys.argv[1:]:
76 with open(filename, "r") as f:
77 all_files += f.read()
78 convert_to_markdown(all_files)
79 else:
80 convert_to_markdown(sys.stdin.read())