|
| 1 | +import os |
| 2 | +import typing as ty |
| 3 | +import tempfile |
| 4 | +import re |
| 5 | +import subprocess as sp |
| 6 | +import shutil |
| 7 | +import tarfile |
| 8 | +from pathlib import Path |
| 9 | +import requests |
| 10 | +import click |
| 11 | +import yaml |
| 12 | + |
| 13 | +RESOURCES_DIR = Path(__file__).parent / "resources" |
| 14 | + |
| 15 | + |
| 16 | +def download_tasks_template(output_path: Path): |
| 17 | + """Downloads the latest pydra-tasks-template to the output path""" |
| 18 | + |
| 19 | + release_url = ( |
| 20 | + "https://api.github.com/repos/nipype/pydra-tasks-template/releases/latest" |
| 21 | + ) |
| 22 | + headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": "nipype2pydra"} |
| 23 | + |
| 24 | + response = requests.get(release_url, headers=headers) |
| 25 | + if response.status_code != 200: |
| 26 | + raise RuntimeError( |
| 27 | + f"Did not find release at '{release_url}'" |
| 28 | + ) |
| 29 | + data = response.json() |
| 30 | + tarball_url = data["tarball_url"] |
| 31 | + |
| 32 | + response = requests.get(tarball_url) |
| 33 | + |
| 34 | + if response.status_code == 200: |
| 35 | + # Save the response content to a file |
| 36 | + with open(output_path, "wb") as f: |
| 37 | + f.write(response.content) |
| 38 | + else: |
| 39 | + raise RuntimeError( |
| 40 | + f"Could not download the pydra-tasks template at {release_url}" |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +@click.command(help="Generates stub pydra packages for all nipype interfaces to import") |
| 45 | +@click.argument("output_dir", type=click.Path(path_type=Path)) |
| 46 | +@click.option("--work-dir", type=click.Path(path_type=Path), default=None) |
| 47 | +@click.option("--task-template", type=click.Path(path_type=Path), default=None) |
| 48 | +def generate_packages( |
| 49 | + output_dir: Path, work_dir: ty.Optional[Path], task_template: ty.Optional[Path] |
| 50 | +): |
| 51 | + |
| 52 | + if work_dir is None: |
| 53 | + work_dir = Path(tempfile.mkdtemp()) |
| 54 | + |
| 55 | + if task_template is None: |
| 56 | + task_template_tar = work_dir / "task-template.tar.gz" |
| 57 | + download_tasks_template(task_template_tar) |
| 58 | + extract_dir = work_dir / "task_template" |
| 59 | + with tarfile.open(task_template_tar, 'r:gz') as tar: |
| 60 | + tar.extractall(path=extract_dir) |
| 61 | + task_template = extract_dir / next(extract_dir.iterdir()) |
| 62 | + |
| 63 | + with open(Path(__file__).parent.parent.parent / "nipype-interfaces-to-import.yaml") as f: |
| 64 | + to_import = yaml.load(f, Loader=yaml.SafeLoader) |
| 65 | + |
| 66 | + # Wipe output dir |
| 67 | + if output_dir.exists(): |
| 68 | + shutil.rmtree(output_dir) |
| 69 | + output_dir.mkdir() |
| 70 | + |
| 71 | + for pkg in to_import["packages"]: |
| 72 | + |
| 73 | + pkg_dir = output_dir / f"pydra-{pkg}" |
| 74 | + pkg_dir.mkdir() |
| 75 | + |
| 76 | + def copy_ignore(_, names): |
| 77 | + return [n for n in names if n in (".git", "__pycache__", ".pytest_cache")] |
| 78 | + |
| 79 | + shutil.copytree(task_template, pkg_dir, ignore=copy_ignore) |
| 80 | + |
| 81 | + auto_conv_dir = pkg_dir / "nipype-auto-conv" |
| 82 | + specs_dir = auto_conv_dir / "specs" |
| 83 | + specs_dir.mkdir(parents=True) |
| 84 | + shutil.copy(RESOURCES_DIR / "nipype-auto-convert.py", auto_conv_dir / "generate") |
| 85 | + os.chmod(auto_conv_dir / "generate", 0o755) # make executable |
| 86 | + |
| 87 | + gh_workflows_dir = pkg_dir / ".github" / "workflows" |
| 88 | + gh_workflows_dir.mkdir(parents=True) |
| 89 | + shutil.copy(RESOURCES_DIR / "pythonpackage.yaml", gh_workflows_dir / "pythonpackage.yaml") |
| 90 | + |
| 91 | + # Add "pydra.tasks.<pkg>.auto to gitignore" |
| 92 | + with open(pkg_dir / ".gitignore", "a") as f: |
| 93 | + f.write("\npydra/tasks/{pkg}/auto") |
| 94 | + |
| 95 | + # rename tasks directory |
| 96 | + (pkg_dir / "pydra" / "tasks" / "CHANGEME").rename(pkg_dir / "pydra" / "tasks" / pkg) |
| 97 | + |
| 98 | + # Replace "CHANGEME" string with pkg name |
| 99 | + for fspath in pkg_dir.glob("**/*"): |
| 100 | + if fspath.is_dir(): |
| 101 | + continue |
| 102 | + with open(fspath) as f: |
| 103 | + contents = f.read() |
| 104 | + contents = re.sub(r"(?<![0-9a-zA-Z])CHANGEME(?![0-9a-zA-Z])", pkg, contents) |
| 105 | + with open(fspath, "w") as f: |
| 106 | + f.write(contents) |
| 107 | + |
| 108 | + for module, interfaces in to_import["interfaces"].items(): |
| 109 | + if module.split("/")[0] != pkg: |
| 110 | + continue |
| 111 | + module_spec_dir = specs_dir.joinpath(*module.split("/")) |
| 112 | + module_spec_dir.mkdir(parents=True) |
| 113 | + for interface in interfaces: |
| 114 | + callables_fspath = module_spec_dir / f"{interface}_callables.py" |
| 115 | + spec_stub = { |
| 116 | + "task_name": interface, |
| 117 | + "nipype_module": "nipype.interfaces." + ".".join(module.split("/")), |
| 118 | + "output_requirements": "# dict[output-field, list[input-field]] : the required input fields for output-field", |
| 119 | + "inputs_metadata": "# dict[input-field, dict[str, Any]] : additional metadata to be inserted into input field", |
| 120 | + "inputs_drop": "# list[input-field] : input fields to drop from the spec", |
| 121 | + "output_templates": "# dict[input-field, str] : \"output_file_template\" to provide to input field", |
| 122 | + "output_callables": f"# dict[output-field, str] : name of function defined in {callables_fspath.name} that retrieves value for output", |
| 123 | + "doctest": "# dict[str, Any]: key-value pairs to provide as inputs to the doctest + the expected value of \"cmdline\" as special key-value pair", |
| 124 | + "tests_inputs": "# List of inputs to pass to tests", |
| 125 | + "tests_outputs": "# list of outputs expected from tests", |
| 126 | + } |
| 127 | + yaml_str = yaml.dump(spec_stub, indent=2, sort_keys=False) |
| 128 | + # strip inserted line-breaks in long strings (so they can be converted to in-line comments) |
| 129 | + yaml_str = re.sub(r"\n ", " ", yaml_str) |
| 130 | + # extract comments after they have been dumped as strings |
| 131 | + yaml_str = re.sub(r"'#(.*)'", r" # \1", yaml_str) |
| 132 | + with open(module_spec_dir / (interface + ".yaml"), "w") as f: |
| 133 | + f.write(yaml_str) |
| 134 | + with open(callables_fspath, "w") as f: |
| 135 | + f.write( |
| 136 | + f'"""Module to put any functions that are referred to in {interface}.yaml"""\n' |
| 137 | + ) |
| 138 | + |
| 139 | + sp.check_call("git init", shell=True, cwd=pkg_dir) |
| 140 | + sp.check_call("git add --all", shell=True, cwd=pkg_dir) |
| 141 | + sp.check_call('git commit -m"initial commit of generated stubs"', shell=True, cwd=pkg_dir) |
| 142 | + sp.check_call("git tag 0.1.0", shell=True, cwd=pkg_dir) |
| 143 | + |
| 144 | + |
| 145 | +if __name__ == "__main__": |
| 146 | + import sys |
| 147 | + |
| 148 | + generate_packages(sys.argv[1:]) |
0 commit comments