|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | +def process_literalinclude(path, language): |
| 5 | + # Make the path relative to the current directory if it starts with ../ |
| 6 | + if path.startswith("../"): |
| 7 | + path = path[3:] # Remove the ../ |
| 8 | + |
| 9 | + if os.path.exists(path): |
| 10 | + with open(path, "r") as code_file: |
| 11 | + code = code_file.read() |
| 12 | + return f".. code-block:: {language}\n\n{code}\n\n" |
| 13 | + else: |
| 14 | + return f".. warning:: File {path} not found\n\n" |
| 15 | + |
1 | 16 | res = "" |
2 | 17 | with open("README_template.rst", "r") as f: |
3 | | - for line in f.readlines(): |
4 | | - line = line.strip("\n").replace(".. include:: ", "") |
5 | | - if line.endswith(".rst"): |
6 | | - tf = open(line, "r").read() |
7 | | - res += tf.replace(".. literalinclude:: ../LICENSE", "").replace("<../LICENSE>", "<LICENSE>").replace(":class:", " ") |
| 18 | + lines = f.readlines() |
| 19 | + i = 0 |
| 20 | + while i < len(lines): |
| 21 | + line = lines[i].strip("\n") |
| 22 | + i += 1 |
| 23 | + |
| 24 | + # Handle include directives |
| 25 | + if line.startswith(".. include:: "): |
| 26 | + include_path = line.replace(".. include:: ", "") |
| 27 | + if include_path.endswith(".rst"): |
| 28 | + with open(include_path, "r") as tf: |
| 29 | + content = tf.read() |
| 30 | + # Process literalinclude directives inside the included file |
| 31 | + content = re.sub(r'\.\. literalinclude:: (.*?)\n\s+:language: (.*?)\n', |
| 32 | + lambda m: process_literalinclude(m.group(1), m.group(2)), content) |
| 33 | + res += content.replace(".. literalinclude:: ../LICENSE", "").replace("<../LICENSE>", "<LICENSE>").replace(":class:", " ") |
| 34 | + # Handle literalinclude directives directly in the template |
| 35 | + elif line.startswith(".. literalinclude:: "): |
| 36 | + # Extract path and language |
| 37 | + path_match = re.match(r'\.\. literalinclude:: (.*)', line) |
| 38 | + if path_match: |
| 39 | + include_path = path_match.group(1) |
| 40 | + # Read the next line to get the language if available |
| 41 | + language = "python" # Default language |
| 42 | + if i < len(lines) and lines[i].strip().startswith(":language:"): |
| 43 | + language = lines[i].strip().replace(":language:", "").strip() |
| 44 | + i += 1 # Skip the language line since we've processed it |
| 45 | + |
| 46 | + res += process_literalinclude(include_path, language) |
8 | 47 | else: |
9 | 48 | res += line + "\n" |
10 | 49 |
|
11 | | - print(res) |
| 50 | +print(res) |
12 | 51 |
|
13 | 52 | with open("README.rst", "w+") as f: |
14 | 53 | f.write(res) |
0 commit comments