|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import subprocess |
| 4 | +from pathlib import Path |
| 5 | +from typing import Literal |
| 6 | + |
| 7 | + |
| 8 | +class ImporterExporter: |
| 9 | + """Imports and exports data while keeping track of it |
| 10 | +
|
| 11 | + This is a class for internal use, but it may mature into a generally useful tool. |
| 12 | + """ |
| 13 | + |
| 14 | + raster_pack_suffixes = (".grass_raster", ".pack", ".rpack", ".grr") |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def is_recognized_file(cls, value): |
| 18 | + """Return `True` if file type is a recognized type, `False` otherwise""" |
| 19 | + return cls.is_raster_pack_file(value) |
| 20 | + |
| 21 | + @classmethod |
| 22 | + def is_raster_pack_file(cls, value): |
| 23 | + """Return `True` if file type is GRASS raster pack, `False` otherwise""" |
| 24 | + if isinstance(value, str): |
| 25 | + return value.endswith(cls.raster_pack_suffixes) |
| 26 | + if isinstance(value, Path): |
| 27 | + return value.suffix in cls.raster_pack_suffixes |
| 28 | + return False |
| 29 | + |
| 30 | + def __init__(self, *, run_function, run_cmd_function): |
| 31 | + self._run_function = run_function |
| 32 | + self._run_cmd_function = run_cmd_function |
| 33 | + # At least for reading purposes, public access to the lists makes sense. |
| 34 | + self.input_rasters: list[tuple[Path, str]] = [] |
| 35 | + self.output_rasters: list[tuple[Path, str]] = [] |
| 36 | + self.current_input_rasters: list[tuple[Path, str]] = [] |
| 37 | + self.current_output_rasters: list[tuple[Path, str]] = [] |
| 38 | + |
| 39 | + def process_parameter_list(self, command, **popen_options): |
| 40 | + """Ingests any file for later imports and exports and replaces arguments |
| 41 | +
|
| 42 | + This function is relatively costly as it calls a subprocess to digest the parameters. |
| 43 | +
|
| 44 | + Returns the list of parameters with inputs and outputs replaced so that a tool |
| 45 | + will understand that, i.e., file paths into data names in a project. |
| 46 | + """ |
| 47 | + # Get processed parameters to distinguish inputs and outputs. |
| 48 | + # We actually don't know the type of the input or outputs) because that is |
| 49 | + # currently not included in --json. Consequently, we are only assuming that the |
| 50 | + # files are meant to be used as in-project data. So, we need to deal with cases |
| 51 | + # where that's not true one by one, such as r.unpack taking file, |
| 52 | + # not raster (cell), so the file needs to be left as is. |
| 53 | + parameters = self._process_parameters(command, **popen_options) |
| 54 | + tool_name = parameters["module"] |
| 55 | + args = command.copy() |
| 56 | + # We will deal with inputs right away |
| 57 | + if "inputs" in parameters: |
| 58 | + for item in parameters["inputs"]: |
| 59 | + if tool_name != "r.unpack" and self.is_raster_pack_file(item["value"]): |
| 60 | + in_project_name = self._to_name(item["value"]) |
| 61 | + record = (Path(item["value"]), in_project_name) |
| 62 | + if ( |
| 63 | + record not in self.output_rasters |
| 64 | + and record not in self.input_rasters |
| 65 | + and record not in self.current_input_rasters |
| 66 | + ): |
| 67 | + self.current_input_rasters.append(record) |
| 68 | + for i, arg in enumerate(args): |
| 69 | + if arg.startswith(f"{item['param']}="): |
| 70 | + arg = arg.replace(item["value"], in_project_name) |
| 71 | + args[i] = arg |
| 72 | + if "outputs" in parameters: |
| 73 | + for item in parameters["outputs"]: |
| 74 | + if tool_name != "r.pack" and self.is_raster_pack_file(item["value"]): |
| 75 | + in_project_name = self._to_name(item["value"]) |
| 76 | + record = (Path(item["value"]), in_project_name) |
| 77 | + # Following the logic of r.slope.aspect, we don't deal with one output repeated |
| 78 | + # more than once, but this would be the place to address it. |
| 79 | + if ( |
| 80 | + record not in self.output_rasters |
| 81 | + and record not in self.current_output_rasters |
| 82 | + ): |
| 83 | + self.current_output_rasters.append(record) |
| 84 | + for i, arg in enumerate(args): |
| 85 | + if arg.startswith(f"{item['param']}="): |
| 86 | + arg = arg.replace(item["value"], in_project_name) |
| 87 | + args[i] = arg |
| 88 | + return args |
| 89 | + |
| 90 | + def _process_parameters(self, command, **popen_options): |
| 91 | + """Get parameters processed by the tool itself""" |
| 92 | + popen_options["stdin"] = None |
| 93 | + popen_options["stdout"] = subprocess.PIPE |
| 94 | + # We respect whatever is in the stderr option because that's what the user |
| 95 | + # asked for and will expect to get in case of error (we pretend that it was |
| 96 | + # the intended run, not our special run before the actual run). |
| 97 | + return self._run_cmd_function([*command, "--json"], **popen_options) |
| 98 | + |
| 99 | + def _to_name(self, value, /): |
| 100 | + return Path(value).stem |
| 101 | + |
| 102 | + def import_rasters(self, rasters, *, env): |
| 103 | + for raster_file, in_project_name in rasters: |
| 104 | + # Overwriting here is driven by the run function. |
| 105 | + self._run_function( |
| 106 | + "r.unpack", |
| 107 | + input=raster_file, |
| 108 | + output=in_project_name, |
| 109 | + superquiet=True, |
| 110 | + env=env, |
| 111 | + ) |
| 112 | + |
| 113 | + def export_rasters( |
| 114 | + self, rasters, *, env, delete_first: bool, overwrite: Literal[True] | None |
| 115 | + ): |
| 116 | + # Pack the output raster |
| 117 | + for raster_file, in_project_name in rasters: |
| 118 | + # Overwriting a file is a warning, so to avoid it, we delete the file first. |
| 119 | + # This creates a behavior consistent with command line tools. |
| 120 | + if delete_first: |
| 121 | + Path(raster_file).unlink(missing_ok=True) |
| 122 | + |
| 123 | + # Overwriting here is driven by the run function and env. |
| 124 | + self._run_function( |
| 125 | + "r.pack", |
| 126 | + input=in_project_name, |
| 127 | + output=raster_file, |
| 128 | + flags="c", |
| 129 | + superquiet=True, |
| 130 | + env=env, |
| 131 | + overwrite=overwrite, |
| 132 | + ) |
| 133 | + |
| 134 | + def import_data(self, *, env): |
| 135 | + # We import the data, make records for later, and the clear the current list. |
| 136 | + self.import_rasters(self.current_input_rasters, env=env) |
| 137 | + self.input_rasters.extend(self.current_input_rasters) |
| 138 | + self.current_input_rasters = [] |
| 139 | + |
| 140 | + def export_data( |
| 141 | + self, *, env, delete_first: bool = False, overwrite: Literal[True] | None = None |
| 142 | + ): |
| 143 | + # We export the data, make records for later, and the clear the current list. |
| 144 | + self.export_rasters( |
| 145 | + self.current_output_rasters, |
| 146 | + env=env, |
| 147 | + delete_first=delete_first, |
| 148 | + overwrite=overwrite, |
| 149 | + ) |
| 150 | + self.output_rasters.extend(self.current_output_rasters) |
| 151 | + self.current_output_rasters = [] |
| 152 | + |
| 153 | + def cleanup(self, *, env): |
| 154 | + # We don't track in what mapset the rasters are, and we assume |
| 155 | + # the mapset was not changed in the meantime. |
| 156 | + remove = [name for (unused, name) in self.input_rasters] |
| 157 | + remove.extend([name for (unused, name) in self.output_rasters]) |
| 158 | + if remove: |
| 159 | + self._run_function( |
| 160 | + "g.remove", |
| 161 | + type="raster", |
| 162 | + name=remove, |
| 163 | + superquiet=True, |
| 164 | + flags="f", |
| 165 | + env=env, |
| 166 | + ) |
| 167 | + self.input_rasters = [] |
| 168 | + self.output_rasters = [] |
0 commit comments