github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/docs/extract_middleware_godocs.py (about)

     1  #!/usr/bin/python3
     2  import os
     3  import re
     4  
     5  
     6  class MiddlewareSourceFile:
     7      def __init__(self, filepath: str):
     8          self._definitions = []
     9          self._filepath = filepath
    10          with open(filepath, 'r') as f:
    11              self._src = f.readlines()
    12              self.name = os.path.basename(self._filepath)
    13  
    14          for (line_no, line) in enumerate(self._src):
    15              # function or struct definitions
    16              if line.startswith('func') or re.match(r'^type \S+? struct', line):
    17                  # with godocs
    18                  if line_no > 0 and (self._src[line_no - 1]).startswith('//'):
    19                      self.add_func_with_godoc(line_no - 1)
    20  
    21      def add_func_with_godoc(self, line_no: int):
    22          func_def = ''
    23  
    24          # find the first line of godoc
    25          while True:
    26              if line_no - 1 > 0 and self._src[line_no - 1].startswith('//'):
    27                  line_no -= 1
    28              else:
    29                  break
    30  
    31          while True:
    32              line_content = self._src[line_no]
    33              func_def += line_content
    34              line_no += 1
    35  
    36              # go fmt, I believe in you
    37              if line_content == '}\n':
    38                  break
    39  
    40          self._definitions.append(func_def)
    41  
    42      def format(self) -> str:
    43          if not self._definitions:
    44              return None
    45  
    46          middleware_name = self.name.strip('.go').replace('_', ' ')
    47          middleware_name = capitalize(middleware_name)
    48          s = '### {}\n\n'.format(middleware_name)
    49  
    50          for func_def in self._definitions:
    51              s += '```go\n{}```\n'.format(func_def)
    52  
    53          return s
    54  
    55  
    56  def capitalize(s: str) -> str:
    57      words = s.split()
    58      for i, word in enumerate(words):
    59          words[i] = word[0].upper() + word[1:]
    60  
    61      return ' '.join(words)
    62  
    63  
    64  if __name__ == '__main__':
    65      go_sources = []
    66      for root, dirs, files in os.walk('../message/router/middleware'):
    67          go_sources = [MiddlewareSourceFile(os.path.join(root, f)) for f in files if f.endswith('.go') and not f.endswith('_test.go')]
    68  
    69      for src_file in go_sources:
    70          formatted = src_file.format()
    71          if formatted:
    72              print(formatted)
    73              print('\n')
    74  
    75      pass