|
9 | 9 | """ |
10 | 10 |
|
11 | 11 | from pathlib import Path |
| 12 | +import os |
12 | 13 | import shutil |
13 | 14 | import sys |
14 | 15 | import tempfile |
|
18 | 19 | from . import markdown |
19 | 20 |
|
20 | 21 |
|
21 | | -OUTPUTTERS = {"kotlin": kotlin.output_kotlin, "markdown": markdown.output_markdown} |
| 22 | +# Each outputter in the table has the following keys: |
| 23 | +# - "output_func": the main function of the outputter, the one which |
| 24 | +# does the actual translation. |
| 25 | +# - "clear_output_dir": a flag to clear the target directory before moving there |
| 26 | +# the generated files. |
| 27 | +OUTPUTTERS = { |
| 28 | + "kotlin": {"output_func": kotlin.output_kotlin, "clear_output_dir": True}, |
| 29 | + "markdown": {"output_func": markdown.output_markdown, "clear_output_dir": False}, |
| 30 | +} |
22 | 31 |
|
23 | 32 |
|
24 | 33 | def translate(input_filepaths, output_format, output_dir, options={}, parser_config={}): |
@@ -49,13 +58,24 @@ def translate(input_filepaths, output_format, output_dir, options={}, parser_con |
49 | 58 | # Write everything out to a temporary directory, and then move it to the |
50 | 59 | # real directory, for transactional integrity. |
51 | 60 | with tempfile.TemporaryDirectory() as tempdir: |
52 | | - OUTPUTTERS[output_format](all_objects.value, Path(tempdir), options) |
| 61 | + tempdir_path = Path(tempdir) |
| 62 | + OUTPUTTERS[output_format]["output_func"]( |
| 63 | + all_objects.value, tempdir_path, options |
| 64 | + ) |
53 | 65 |
|
54 | | - if output_dir.is_file(): |
55 | | - output_dir.unlink() |
56 | | - elif output_dir.is_dir(): |
57 | | - shutil.rmtree(output_dir) |
| 66 | + if OUTPUTTERS[output_format]["clear_output_dir"]: |
| 67 | + if output_dir.is_file(): |
| 68 | + output_dir.unlink() |
| 69 | + elif output_dir.is_dir(): |
| 70 | + shutil.rmtree(output_dir) |
58 | 71 |
|
59 | | - shutil.copytree(tempdir, output_dir) |
| 72 | + shutil.copytree(tempdir, output_dir) |
| 73 | + else: |
| 74 | + # We can't use shutil.copytree alone if the directory already exists. |
| 75 | + # However, if it doesn't exist, make sure to create one otherwise |
| 76 | + # shutil.copy will fail. |
| 77 | + os.makedirs(output_dir, exist_ok=True) |
| 78 | + for filename in tempdir_path.glob("*"): |
| 79 | + shutil.copy(filename, output_dir) |
60 | 80 |
|
61 | 81 | return 0 |
0 commit comments