diff options
Diffstat (limited to 'src/parser.py')
| -rw-r--r-- | src/parser.py | 564 |
1 files changed, 564 insertions, 0 deletions
diff --git a/src/parser.py b/src/parser.py new file mode 100644 index 0000000..dffba84 --- /dev/null +++ b/src/parser.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +""" Parser for the file with specification for the map""" +import argparse +from argparse import Namespace +from pathlib import Path + +from models import Connection, MapData, Zone, ZoneType + + +class ParseError(Exception): + """Parsing errors""" + pass + + +class Parser: + """Parse a drone map file into a MapData instance.""" + + VALID_KEYS = { + "nb_drones", + "start_hub", + "end_hub", + "hub", + "connection", + } + + def __init__(self) -> None: + self.args = self.parse_args() + + def parse_map(self) -> MapData: + """Parse the input file and return a validated MapData.""" + + lines = self._read_file() + lines = self._clean_lines(lines) + + self._check_keys_valid(lines) + + nb_drones = self._parse_nb_drones(lines) + + start = self._parse_start_end_zone( + lines, + nb_drones, + is_start=True, + ) + + end = self._parse_start_end_zone( + lines, + nb_drones, + is_start=False, + ) + + zones = self._parse_zones( + lines, + nb_drones, + start, + end, + ) + + connections = self._parse_connections( + lines, + zones, + start, + end, + ) + return MapData( + nb_drones=nb_drones, + start=start, + end=end, + zones=zones, + connections=connections, + ) + + def parse_args(self) -> Namespace: + """Parse command-line arguments and return a + 'method that runs the parser and places the + extracted data in a 'argparse.Namespace' + object' see argparse documention. + """ + + parser = argparse.ArgumentParser() + parser.add_argument( + "filename", + type=Path, + help="Path to the map file" + ) + return parser.parse_args() + + def _read_file(self) -> list[str]: + """Read all lines from the input file. + Returns a list of lines. + """ + + filename: Path = self.args.filename + + if not filename.exists(): + raise FileNotFoundError( + f"Map file not found: {filename}" + ) + + if not filename.is_file(): + raise ValueError( + f"Not a regular file: {filename}" + ) + + try: + lines = filename.read_text().splitlines() + except PermissionError: + raise PermissionError( + f"Check the permission of file: {filename}" + ) + except OSError: + raise OSError( + f"Unable to read map file: {filename}" + ) + + if not lines: + raise ValueError( + f"Map file is empty: {filename}" + ) + + return lines + + def _clean_lines(self, lines: list[str]) -> list[str]: + """ + Remove blank lines and comments. + Inline comments are also removed. + Returns a list of 'cleaned' lines. + """ + + cleaned: list[str] = [] + + for line in lines: + if line.startswith('#'): + continue + + if line: + cleaned.append(line) + + return cleaned + + def _check_keys_valid(self, lines: list[str]) -> None: + """Check that every line starts with a supported map key. + The start_hub, end_hub, and nb_drones keys may each appear only once. + init seen_keys + add key to seen_keys + check whether new key is already in seen_keys + + Second arg of split is 'maxsplit'. + + See top of the file for VALID_KEYS. + """ + + unique_keys = {"start_hub", "end_hub", "nb_drones"} + seen_keys: set[str] = set() + + for line in lines: + if ":" not in line: + raise ValueError( + f"Invalid line; expected '<key>: ...': {line}" + ) + + key = line.split(":", 1)[0].strip() + + if key not in self.VALID_KEYS: + raise ValueError( + f"Unknown map key '{key}' in line: {line}" + ) + + if key in unique_keys: + if key in seen_keys: + raise ValueError( + f"Duplicate map key '{key}': {line}" + ) + + seen_keys.add(key) + + def _parse_nb_drones(self, lines: list[str]) -> int: + """Extract and validate the number of drones.""" + + if not lines[0].startswith("nb_drones"): + raise ParseError( + "ParseError: The first line does not define" + "the number of drones." + ) + + value = lines[0].split(":", 1)[1].strip() + + try: + nb_drones = int(value) + except ValueError: + raise ValueError( + f"Invalid number of drones: {value!r}" + ) + + if nb_drones <= 0: + raise ValueError( + "The number of drones must be greater than zero." + ) + + return nb_drones + + def _parse_start_end_zone( + self, + lines: list[str], + nb_drones: int, + is_start: bool = False, + ) -> Zone: + """Check whether zone is start or end. + Extract the line. + Extract and process the start or end zone.""" + + zone_key = "start_hub" if is_start else "end_hub" + + line = self._get_line(lines, zone_key) + + return self._process_zone_line( + line=line, + nb_drones=nb_drones, + zone=zone_key, + is_start=is_start, + is_end=not is_start, + ) + + def _get_line( + self, + lines: list[str], + zone: str, + ) -> str: + """Return the unique start_hub or end_hub line. + Raise an error if start_* or end_hub is not defined. + Raise an error if multiple start_* or end_hub are defined. + """ + + count = 0 + for line in lines: + if line.startswith(zone): + count += 1 + matching_line = line + + if count == 0: + raise ParseError( + f"ParseError: No {zone} defined." + ) + elif count > 1: + raise ParseError( + f"ParseError: Multiple {zone}s defined." + ) + + return matching_line + + def _process_zone_line( + self, + line: str, + nb_drones: int, + zone: str = "zone", + is_start: bool = False, + is_end: bool = False, + ) -> Zone: + """ + Parse a zone line and return a zone object. + + Supported format: + + hub: name x y [zone=restricted color=blue max_drones=3] + hub: name x y [color=blue max_drones=3] + hub: name x y [color=blue] + start_hub: name x y [color=green] + end_hub: name x y [color=red] + + About split(): If maxsplit is given, at most maxsplit + splits are done (thus, the list will have at most + maxsplit+1 elements). + """ + + expected_prefix = f"{zone}:" + + if not line.startswith(expected_prefix): + raise ValueError( + f"Expected a '{zone}' line, got: {line}" + ) + + after_column = line[len(expected_prefix):].strip() + + # zone_type is default if unspecified + zone_type: ZoneType = ZoneType.NORMAL + color: str | None = None + max_drones = nb_drones if is_start or is_end else 1 + + parts = after_column.split(maxsplit=3) + + # without metadata + if len(parts) == 3: + name, x_value, y_value = parts + + # with metadata + elif len(parts) == 4 \ + and parts[3].startswith('[') \ + and parts[3].endswith(']'): + name, x_value, y_value, metadata = parts + metadata = metadata.strip("[]") + pairs = metadata.split(" ") + + for pair in pairs: + try: + # split metadata pairs + key, value = pair.split("=", 1) + except ValueError: + raise ValueError( + f"Invalid metadata: '{pair}' " + f"for zone '{name}'. " + f"Must be 'key=value'." + ) + key = key.strip().lower() + value = value.strip() + + if key == "color": + color = value + elif key == "zone": + try: + zone_type = ZoneType[value.upper()] # Enum lookup + except KeyError: + raise ParseError( + f"ParseError: Invalid zone type '{value}' " + f"for zone '{name}'." + ) + elif key == "max_drones": + try: + max_drones = int(value) + except ValueError: + raise ValueError( + f"Invalid max_drones value: '{value}'" + f"for zone '{name}'. " + f"Must be an integer." + ) + else: + raise ValueError( + f"Invalid key: '{key}'" + ) + else: + raise ValueError( + f"Invalid syntax for line: '{line}'. " + f"Should be <zone>: <name> <x> <y> [...]. " + f"<name> should not have spaces or dashes." + ) + try: + x = int(x_value) + y = int(y_value) + except ValueError: + raise ValueError( + f"Zone coordinates must be integers: {line}" + ) + + return Zone( + name=name, + x=x, + y=y, + color=color, + zone_type=zone_type, + max_drones=max_drones, + is_start=is_start, + is_end=is_end, + ) + + def _parse_zones( + self, + lines: list[str], + nb_drones: int, + start: Zone, + end: Zone, + ) -> list[Zone]: + """Parse all ordinary zone lines.""" + + zones: list[Zone] = [] + + for line in lines: + if not line.startswith("hub:"): + continue + + zone = self._process_zone_line( + line=line, + nb_drones=nb_drones, + zone="hub", + ) + + zones.append(zone) + + self._verify_unique_zone(zones, start, end) + + return zones + + def _verify_unique_zone( + self, + zones: list[Zone], + start: Zone, + end: Zone, + ) -> bool: + """Ensure that all zone names and coordinates are unique.""" + + all_zones = [start, end, *zones] + + names = [zone.name for zone in all_zones] + + if len(names) != len(set(names)): + raise ValueError( + "Zone names must be unique." + ) + + coordinates = [ + (zone.x, zone.y) + for zone in all_zones + ] + + if len(coordinates) != len(set(coordinates)): + raise ValueError( + "Zone coordinates must be unique." + ) + + return True + + def _parse_connections( + self, + lines: list[str], + zones: list[Zone], + start: Zone, + end: Zone, + ) -> list[Connection]: + """Parse all connection lines.""" + + connections: list[Connection] = [] + + for line in lines: + if not line.startswith("connection:"): + continue + + connection = self._process_conn_line( + line=line, + zones=zones, + start=start, + end=end, + ) + + connections.append(connection) + + if self._check_duplicated_connections(connections): + raise ParseError("ParseError: Duplicated connections.") + + return connections + + def _process_conn_line( + self, + line: str, + zones: list[Zone], + start: Zone, + end: Zone, + ) -> Connection: + """Parse a connection line.""" + + prefix = "connection:" + + if not line.startswith(prefix): + raise ValueError( + f"Invalid connection line: {line}" + ) + + value = line[len(prefix):].strip() + link_capacity_raw: str | None = None + link_capacity_value: int = 1 + + if len(value.split(" ")) > 1: + conn_pair, link_capacity_raw = value.split(" ") + else: + conn_pair = value + + if conn_pair.count("-") != 1: + raise ValueError( + f"Invalid connection definition: {line}. " + "Expected 'connection: zone1-zone2'." + ) + + src_name, dest_name = [ + part.strip() + for part in conn_pair.split("-", 1) + ] + + all_zones = [start, end, *zones] + zone_by_name = { + zone.name: zone + for zone in all_zones + } + + if src_name not in zone_by_name: + raise ValueError( + f"Unknown source zone '{src_name}' in: {line}" + ) + + if dest_name not in zone_by_name: + raise ValueError( + f"Unknown destination zone '{dest_name}' in: {line}" + ) + + src = zone_by_name[src_name] + dest = zone_by_name[dest_name] + + # Store the connection name on both endpoint zones. + connection_name = f"{src.name}-{dest.name}" + + if connection_name not in src.connections: + src.connections.append(connection_name) + + reverse_name = f"{dest.name}-{src.name}" + + if reverse_name not in dest.connections: + dest.connections.append(reverse_name) + + if link_capacity_raw: + try: + link_capacity_pair = link_capacity_raw.strip("[]") + key, link_capacity_value_str = link_capacity_pair.split("=") + # convert to a str to make mypy happy + link_capacity_value = int(link_capacity_value_str) + except ValueError: + raise ValueError( + f"Capacity must be an int: {link_capacity_value}" + ) + + return Connection( + src=src, + dest=dest, + link_capacity=link_capacity_value + ) + + def _check_duplicated_connections( + self, + connections: list[Connection], + ) -> bool: + """Ensure that a connection is not defined more than once + Use frozenset() so that pairs of endpoints are hashable. + A -> B and B -> A produce the same key. + See README for more info. + """ + seen: set[frozenset[str]] = set() + + for connection in connections: + key = frozenset({ + connection.src.name, + connection.dest.name, + }) + + if key in seen: + raise ValueError( + "Duplicated connection found: " + f"{connection.src.name}-{connection.dest.name}" + ) + + seen.add(key) + + return False + + +if __name__ == "__main__": + try: + drone_map = Parser().parse_map() + print(drone_map.model_dump_json(indent=2)) + except (ValueError, FileNotFoundError, OSError) as err: + raise SystemExit(f"Error: {err}") |
