summaryrefslogtreecommitdiff
path: root/src/parser.py
blob: dffba84616ee46767bff892947b41dd031d81235 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
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}")