#!/usr/bin/env python3 import sys import os def get_source_files_recursive(path): source_files = [] for dirpath, _, filenames in os.walk(path): for filename in filenames: ext = os.path.splitext(filename)[1] if ext == ".c" or ext == ".h": full_path = os.path.join(dirpath, filename) source_files.append(full_path) return source_files def lstrip_lines(string): result = [] for line in string.splitlines(): result.append(line.lstrip()) if len(result) > 0: if len(result[0].strip()) == 0: del result[0] if len(result[-1].strip()) == 0: del result[-1] return "\n".join(result) def extract_docs(filepath): file_content = "" with open(filepath, "r") as file: file_content = file.read() docs = [] search_index = 0 while True: index = file_content.find("/*doc(", search_index) if index == -1: break index += 6 doc_name_end = len(file_content) for i, c in enumerate(file_content[index:]): if c == ')': doc_name_end = index + i break doc_name = file_content[index:doc_name_end] doc_name_end += 1 end = file_content.find("*/", doc_name_end) if end == -1: break doc = file_content[doc_name_end:end] search_index = end + 2 docs.append((doc_name, lstrip_lines(doc))) return docs def main(): script_path = os.path.realpath(sys.argv[0]) script_dir = os.path.dirname(script_path) amalgam_base = os.path.dirname(script_dir) amalgam_includes = os.path.join(amalgam_base, "include") amalgam_sources = os.path.join(amalgam_base, "src") source_files = get_source_files_recursive(amalgam_includes) source_files += get_source_files_recursive(amalgam_sources) for filepath in source_files: docs = extract_docs(filepath) for doc in docs: doc_path = os.path.join(script_dir, doc[0] + ".md") with open(doc_path, "w") as file: file.write(doc[1]) print("Wrote doc for %s into file %s" % (doc[0], doc_path)) if __name__ == "__main__": main()