summaryrefslogtreecommitdiff
path: root/tools/compress_ranges.py
blob: c99309a0f39959677a8b028dcb6b393f6d8bf0d5 (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
#!/usr/bin/env python3

# SPDX-FileCopyrightText: © 2023 ZeldaRET
# SPDX-License-Identifier: MIT

from __future__ import annotations

import argparse
import itertools
from pathlib import Path
import sys
import yaml


QUIET = False

def printVerbose(*args, **kwargs):
    if QUIET:
        return
    print(*args, **kwargs)


def ranges(i):
    for _, b in itertools.groupby(enumerate(i), lambda pair: pair[1] - pair[0]):
        b = list(b)
        yield b[0][1], b[-1][1]


def getCompressedSegmentIndices(yamlPath: Path):
    printVerbose("Finding compressed segments...")
    with yamlPath.open() as f:
        yamlObj = yaml.load(f, Loader=yaml.SafeLoader)

    indices = []
    currentIndex = 0
    for segment in yamlObj["segments"]:
        if not isinstance(segment, dict):
            continue

        notInDma = segment.get("notdma", False)
        if notInDma:
            continue

        shouldCompress = segment.get("compress", False)
        if shouldCompress:
            indices.append(currentIndex)
        currentIndex += 1
    return list(ranges(indices))


def main():
    # Args from command line
    parser = argparse.ArgumentParser(description="Compress ROM")

    parser.add_argument("yaml", help="Path to the yaml file", type=Path)
    parser.add_argument('-o', '--outfile', help='output file to write to. None for stdout')

    args = parser.parse_args()

    compressed_ranges = getCompressedSegmentIndices(args.yaml)
    indicesList = []
    for start, end in compressed_ranges:
        if start != end:
            indicesList.append(f"{start}-{end}")
        else:
            indicesList.append(f"{start}")

    if args.outfile is None:
        sys.stdout.write(','.join(indicesList))
        sys.stdout.write("\n")
    else:
        with open(args.outfile, "w") as f:
            f.write(','.join(indicesList))
            f.write("\n")

    return 0


if __name__ == "__main__":
    exit(main())