parse_commands.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os
  2. from dataclasses import dataclass
  3. import yaml
  4. @dataclass()
  5. class Command:
  6. name: str
  7. docstring: str | None = None
  8. signature: str | None = None
  9. def parse_command_file() -> str | None:
  10. if not os.path.exists('commands.sh'):
  11. return None
  12. content = open('commands.sh', 'r').read()
  13. lines = content.split('\n')
  14. commands: list[Command] = []
  15. idx = 0
  16. docs: list[str] = []
  17. while idx < len(lines):
  18. line = lines[idx]
  19. idx += 1
  20. if line.startswith('# '):
  21. docs.append(line[2:])
  22. elif line.strip().endswith('() {'):
  23. name = line.split()[0][:-2]
  24. while lines[idx].strip() != '}':
  25. idx += 1
  26. docstring, signature = None, name
  27. docs_dict = yaml.safe_load('\n'.join(docs).replace('@yaml', ''))
  28. if docs_dict is not None:
  29. docstring = docs_dict.get('docstring')
  30. arguments = docs_dict.get('arguments', None)
  31. if 'signature' in docs_dict:
  32. signature = docs_dict['signature']
  33. else:
  34. if arguments is not None:
  35. for param, settings in arguments.items():
  36. if 'required' in settings:
  37. signature += f' <{param}>'
  38. else:
  39. signature += f' [<{param}>]'
  40. command = Command(name, docstring, signature)
  41. commands.append(command)
  42. docs = []
  43. function_docs = ''
  44. for cmd in commands:
  45. if cmd.docstring is not None:
  46. function_docs += f'{cmd.signature or cmd.name} - {cmd.docstring}\n'
  47. return function_docs